Python Numpy.square() - 平方

Jinku Hu 2023年1月30日 2020年6月17日
  1. numpy.square() 语法
  2. 示例代码:numpy.square()
  3. 示例代码:numpy.square(),参数为 out
  4. 示例代码: numpy.square() 输入为负数情况
  5. 示例代码:numpy.square() 输入为复数情况
Python Numpy.square() - 平方

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

它是 Numpy.sqrt() 方法的逆操作。

numpy.square() 语法

numpy.square(arr,
          out=None) 

参数

arr 输入数组
out 如果给定了 out,结果将存储在 out 中。out 应与 arr 形状相同。

返回结果

它返回输入数组中每个元素的平方的数组,即使给定 out 也是如此。

示例代码: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() 方法也返回平方数组,如上图所示。

如果 outarr 的形状不一样,就会引发 ValueError

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):
  File "C:\Test\test.py", line 6, in <module>
    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]
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn