# Python Numpy.sqrt() - 平方根

`Numpy.sqrt()` 函数计算给定数组中每个元素的平方根

## `numpy.sqrt()` 语法

``````numpy.sqrt(arr,
out=None)
``````

### 参数

`arr` 输入阵列
`out` 如果给定了 `out`，结果将存储在 `out` 中。`out` 应与 `arr` 形状相同

## 示例代码：`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()` 方法也返回平方根数组，如上图所示。

``````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):
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]
``````

## 示例代码：`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()` 方法只返回一个平方根，它有一个正的实数。