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