Python math.sqrt() 方法



Python math.sqrt() 方法用於獲取給定值的平方根。一個數的平方根是指將該數自身相乘得到該數的因子。求一個數的平方根與對一個數進行平方運算相反。

例如,數字 5 和 -5 都是 25 的平方根,因為 52= (-5)2 = 25。

注意 - 此函式無法直接訪問,因此我們需要匯入 math 模組,然後使用 math 靜態物件呼叫此函式。

語法

以下是 Python math.sqrt() 方法的語法:

math.sqrt(x)

引數

  • x - 這是任何大於或等於 0 的數字。

返回值

此方法返回給定數字的平方根。

示例

以下示例演示了 Python math.sqrt() 方法的用法。在這裡,我們嘗試傳遞不同的正值,並使用此方法找到它們的平方根。

# This will import math module
import math   
print "math.sqrt(100) : ", math.sqrt(100)
print "math.sqrt(7) : ", math.sqrt(7)
print "math.sqrt(math.pi) : ", math.sqrt(math.pi)

執行上述程式時,會產生以下結果:

math.sqrt(100) :  10.0
math.sqrt(7) :  2.64575131106
math.sqrt(math.pi) :  1.77245385091

示例

如果我們將小於零的數字傳遞給 sqrt() 方法,則會返回 ValueError。

在這裡,我們建立一個值為 '-1' 的物件 'num'。然後我們將此 num 作為引數傳遞給該方法。

# importing the module
import math
num = -1
# taking a number less than zero
res = math.sqrt(num)
# printing the result
print('The square root of negative number is:',res)

執行上述程式碼時,我們得到以下輸出:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 5, in <module>
    res = math.sqrt(-1)
ValueError: math domain error

示例

在這裡,我們將 0 作為引數傳遞給 sqrt() 方法。它將值 0.0 作為結果返回。

# importing the module
import math
num = 0
# taking a number less than zero
res = math.sqrt(num)
# printing the result
print('The square root of zero is:',res)

以下是上述程式碼的輸出:

The square root of zero is: 0.0

示例

如果我們將複數傳遞給 sqrt() 方法,則會返回 TypeError。

在這裡,我們建立一個值為 '6 + 4j' 的物件 'x'。然後我們將此 num 作為引數傳遞給該方法。

# importing the module
import math
x = 6 + 4j
res = math.sqrt(x)
print( "The square root of a complex number is:", res)

上述程式碼的輸出如下:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 4, in <module>
    res = math.sqrt(x)
TypeError: must be real number, not complex
python_maths.htm
廣告