在 Python 中使用 math.sqrt()、cmath 和 NumPy 計算平方根

稱呼數學.sqrt()在 Python 中計算實數平方根。對於負值或複數輸入,切換到cmath.sqrt()。當您需要數組的元素根時,請使用numpy.sqrt();對於純整數結果(根的下限),請使用數學.isqrt().

方法 1 — 使用 math.sqrt() 計算非負實數

步驟一:導入標準math模組。

import math

步驟2:稱呼math.sqrt(x)與一個int或者float得到一個float結果。

math.sqrt(49)      # 7.0
math.sqrt(70.5)    # 8.396427811873332
math.sqrt(0)       # 0.0

步驟3:處理負面輸入;math.sqrt提高ValueError為了x < 0.

def safe_sqrt(x):
    import math
    try:
        return math.sqrt(x)
    except ValueError:
        return "Use cmath.sqrt() for negatives."

第4步:應用於現實世界的計算(畢達哥拉斯定理)。

a, b = 27, 39
run_distance = math.sqrt(a**2 + b**2)  # 47.43416490252569

方法 2 — 使用 cmath.sqrt() 進行負數或複數輸入

步驟一:進口cmath用於複數支援。

import cmath

步驟2:稱呼cmath.sqrt(x)對於負數或複數;它總是傳回一個複數值。

cmath.sqrt(-25)     # 5j
cmath.sqrt(8j)       # (2+2j)

步驟3:透過存取組件result.realresult.imag如果需要的話。

z = cmath.sqrt(-4)
z.real, z.imag      # (0.0, 2.0)

方法 3 — 使用 NumPy 對陣列進行向量化平方根

步驟一:導入 NumPy。

import numpy as np

步驟2:計算元素根np.sqrt;傳遞數組或標量。

arr = np.array([4, 9, 16, 25])
np.sqrt(arr)        # array([2., 3., 4., 5.])

步驟3:處理負面因素:np.sqrt給出nan對於負實數;使用np.emath.sqrt()或轉換為複雜。

a = np.array([4, -1, np.inf])
np.sqrt(a)              # [ 2., nan, inf]
np.emath.sqrt(a)        # [ 2.+0.j,  0.+1.j, inf+0.j]
np.sqrt(a.astype(complex))  # [ 2.+0.j,  0.+1.j, inf+0.j]

方法 4 — 當無法匯入模組時使用指數運算子或 pow()

步驟一:提高到二分之一次方電力營運商.

9 ** 0.5     # 3.0
2 ** 0.5     # 1.4142135623730951

步驟2:尊重否定的優先順序;需要使用括號以避免在求冪後應用一元減法。

-4 ** 0.5      # -2.0  (interpreted as -(4 ** 0.5))
(-4) ** 0.5    # (1.2246467991473532e-16+2j)  complex result

步驟3:或者,使用pow(x, 0.5)對非負輸入具有相同的效果。

pow(16, 0.5)   # 4.0

方法 5 — 取得整數平方根(下限)以進行精確的整數數學運算

步驟一:使用math.isqrt(n)求非負整數的整數平方根(下限)。

import math
math.isqrt(10)   # 3  (since 3*3 = 9 ≤ 10 < 4*4)

步驟2:通過一次比較檢查完美平方。

n = 49
r = math.isqrt(n)
is_perfect_square = (r * r == n)   # True

注意事項和陷阱

  • math.sqrt()適用於實數、非負輸入並返回浮點數;零有效。
  • 需要負輸入cmath.sqrt()以獲得複雜的結果。
  • numpy.sqrt()對於數組來說是向量化且快速的;負實際值產生nan除非你使用np.emath.sqrt()或複雜的資料類型。
  • 指數運算符**pow()可以計算平方根,但不太明確;更喜歡math.sqrt()為了可讀性和通常更好的速度。
  • 對於非常大的整數,浮點結果可能不精確;使用math.isqrt()以獲得精確的整數層結果。

挑選math.sqrt()對於標準實數輸入,cmath.sqrt()對於負數/複數值,以及numpy.sqrt()當您需要向量化操作時;使用math.isqrt()對於精確的整數樓層。