# Python Numpy.square() - 平方

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

## `numpy.square()` 语法。

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

### 参数

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

## 示例代码：`numpy.square()`

``````import numpy as np

arr = [1, 3, 5, 7]

arr_sq = np.square(arr)

print(arr_sq)
``````

``````[ 1  9 25 49]
``````

## 示例代码：`numpy.square()`，参数为 `out`

``````import numpy as np

arr = [1, 3, 5, 7]
out_arr = np.zeros(4)

arr_sq = np.square(arr, out_arr)

print(out_arr)
print(arr_sq)
``````

``````[ 1  9 25 49]
[ 1  9 25 49]
``````

`out_arr` 的形状与 `arr` 相同，`arr` 的平方被保存在其中。

`numpy.square()` 方法也返回平方数组，如上图所示。

``````import numpy as np

arr = [1, 3, 5, 7]
out_arr = np.zeros(3)

arr_sq = np.square(arr, out_arr)

print(out_arr)
print(arr_sq)
``````

``````Traceback (most recent call last):
arr_sq = np.square(arr, out_arr)
ValueError: operands could not be broadcast together with shapes (4,) (3,)
``````

## 示例代码： `numpy.square()` 输入为负数情况

``````import numpy as np

arr = [-1, -3, -5, -7]

arr_sq = np.square(arr)

print(arr_sq)
``````

``````[ 1  9 25 49]
``````

## 示例代码：`numpy.square()` 输入为复数情况

``````import numpy as np

arr = [1+2j, -2-1j, 2-3j, -3+4j]

arr_sq = np.square(arr)

print(arr_sq)
``````

``````[-3. +4.j  3. +4.j -5.-12.j -7.-24.j]
``````