Python Numpy.sqrt() - 平方根
-
numpy.sqrt()語法 -
示例程式碼:
numpy.sqrt() -
示例程式碼:
numpy.sqrt(),引數為out -
示例程式碼:
numpy.sqrt()與負數的關係 -
示例程式碼:
numpy.sqrt()與複數一起使用
Numpy.sqrt() 函式計算給定陣列中每個元素的平方根。
它是 Numpy.square() 方法的逆操作。
numpy.sqrt() 語法
numpy.sqrt(arr, out=None)
引數
arr |
輸入陣列 |
out |
如果給定了 out,結果將儲存在 out 中。out 應與 arr 形狀相同 |
返回結果
它返回輸入陣列中每個元素的平方根陣列,即使給定 out 也是如此。
示例程式碼:numpy.sqrt()
import numpy as np
arr = [1, 9, 25, 49]
arr_sqrt = np.sqrt(arr)
print(arr_sqrt)
輸出:
[1. 3. 5. 7.]
示例程式碼:numpy.sqrt(),引數為 out
import numpy as np
arr = [1, 9, 25, 49]
out_arr = np.zeros(4)
arr_sqrt = np.sqrt(arr, out_arr)
print(out_arr)
print(arr_sqrt)
輸出:
[1. 3. 5. 7.]
[1. 3. 5. 7.]
out_arr 的形狀與 arr 相同,arr 的平方根儲存在其中。而 numpy.sqrt() 方法也返回平方根陣列,如上圖所示。
如果 out 與 arr 的形狀不一樣,就會引發 ValueError。
import numpy as np
arr = [1, 9, 25, 49]
out_arr = np.zeros((2, 2))
arr_sqrt = np.sqrt(arr, out_arr)
print(out_arr)
print(arr_sqrt)
輸出:
Traceback (most recent call last):
File "C:\Test\test.py", line 6, in <module>
arr_sqrt = np.sqrt(arr, out_arr)
ValueError: operands could not be broadcast together with shapes (4,) (2,2)
示例程式碼:numpy.sqrt() 與負數的關係
import numpy as np
arr = [-1, -9, -25, -49]
arr_sqrt = np.sqrt(arr)
print(arr_sqrt)
輸出:
Warning (from warnings module):
File "..\test.py", line 5
arr_sqrt = np.sqrt(arr)
RuntimeWarning: invalid value encountered in sqrt
[nan nan nan nan]
當輸入是負數時,它會丟擲一個 RuntimeWarning,並返回 nan 作為結果。
示例程式碼:numpy.sqrt() 與複數一起使用
import numpy as np
arr = [3 + 4j, -5 + 12j, 8 - 6j, -15 - 8j]
arr_sqrt = np.sqrt(arr)
print(arr_sqrt)
輸出:
[2.+1.j 2.+3.j 3.-1.j 1.-4.j]
一個複數有兩個平方根例如:

numpy.sqrt() 方法只返回一個平方根,它有一個正的實數。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
