logo

Python math.sqrt() 関数 | Python で平方根を求める

sqrt() 関数の戻り値 任意の数の平方根 。これは、Python プログラミング言語の組み込み関数です。

この記事では、平方根を求める Python プログラムについて詳しく学習します。



sqrt() 関数

math モジュールの sqrt() 関数を使用して、Python で平方根を計算できます。この例では、sqrt() 関数を使用してさまざまな数値の平方根を計算しています。

Python3








# Python3 program to demonstrate the> # sqrt() method> # import the math module> import> math> # print the square root of 0> print>(math.sqrt(>0>))> # print the square root of 4> print>(math.sqrt(>4>))> # print the square root of 3.5> print>(math.sqrt(>3.5>))>

>

>

出力

CSSテキストの整列
0.0 2.0 1.8708286933869707>

math.sqrt() 関数の定義

Python の sqrt() 関数は組み込み関数であり、数学ライブラリに存在します。

数学ライブラリをインポートした後、sqrt 関数を使用できるようになります。

import math>

sqrt() 関数は 0 以上の値のみを受け取ります。

math.sqrt() メソッドの構文

math.sqrt(x)

パラメータ

バツ: x>=0 のような任意の数値です。

戻り値: 私 t は、パラメータに渡された数値の平方根を返します。

sqrt() 関数の例

math.sqrt() 関数のさまざまな使用法をいくつか見てみましょう。

例 1: プライムかどうかを確認する

この例では、数値が与えられ、その数値が素数かどうかをチェックしています。ここでは、2 から sqrt(n) までのループを実行し、範囲 (2-sqrt(n)) 内の数値が n を割るかどうかを確認します。

Python3




# Python program for practical application of sqrt() function> # import math module> import> math> # function to check if prime or not> def> check(n):> >if> n>=>=> 1>:> >return> False> > ># from 1 to sqrt(n)> >for> x>in> range>(>2>, (>int>)(math.sqrt(n))>+>1>):> >if> n>%> x>=>=> 0>:> >return> False> >return> True> # driver code> n>=> 23> if> check(n):> >print>(>'prime'>)> else>:> >print>(>'not prime'>)>

>

スパークチュートリアル

>

出力

prime>

例 2: 三角形の斜辺を求める

この例では、sqrt() 関数を使用して三角形の斜辺を求めています。

Python3




a>=> 10> b>=> 23> import> math> # importing the math module> c>=> math.sqrt(a>*>*> 2> +> b>*>*> 2>)> print>(>'The value for the hypotenuse would be '>, c)>

>

>

出力

The value for the hypotenuse would be 25.079872407968907>

sqrt() 関数エラー

x<0 の場合、実行時エラーのため実行されません。この例では、数値が 0 未満の場合、Python 平方根を計算できないことがわかります。

Python3




# Python3 program to demonstrate the error in> # sqrt() method> # import the math module> import> math> # print the error when x<0> print>(math.sqrt(>->1>))>

>

>

セッションの有効期限が切れています

出力

Traceback (most recent call last): File '/home/67438f8df14f0e41df1b55c6c21499ef.py', line 8, in print(math.sqrt(-1)) ValueError: math domain error>

以上、Python で平方根を求めるために使用される sqrt() 関数について説明しました。この組み込み関数を使用すると、Python で平方根を求めるのが非常に簡単になります。

その他の数学ライブラリ関数については、Python 数学モジュールを参照してください。