API · NumPy

Python Numpy.sqrt() - 平方根

Python numpy.sqrt()函数计算一个 numpy 数组的平方根。

本页内容

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 示例

numpy.sqrt() 方法只返回一个平方根,它有一个正的实数。