API · NumPy

Python Numpy.square() - Quadrat

Die Python-Funktion numpy.square() berechnet das Quadrat eines numpy-Arrays.

Die Funktion Numpy.square() berechnet das Quadrat jedes Elements in der gegebenen Matrix.

Es handelt sich um die inverse Operation der Methode Numpy.sqrt().

Syntax von numpy.square()

numpy.square(arr, out=None)

Parameter

arr Eingabe-Array
out Wenn out angegeben wird, wird das Ergebnis in out gespeichert. out sollte die gleiche Form wie arr haben.

Zurück

Es gibt ein Array mit dem Quadrat jedes Elements im Eingabe-Array zurück, auch wenn out angegeben ist.

Beispiel-Codes: numpy.square()

import numpy as np

arr = [1, 3, 5, 7]

arr_sq = np.square(arr)

print(arr_sq)

Ausgabe:

[ 1  9 25 49]

Beispielcodes: numpy.square() Mit Parameter 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)

Ausgabe:

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

out_arr hat die gleiche Form wie arr, und das Quadrat von arr wird darin gespeichert.

Und die Methode numpy.square() gibt ebenfalls das Quadrat-Array zurück, wie oben gezeigt.

Wenn out nicht die gleiche Form wie arr hat, wird ein ValueError ausgegeben.

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)

Ausgabe:

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,) 

Beispiel-Codes: numpy.square() mit negativen Zahlen

import numpy as np

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

arr_sq = np.square(arr)

print(arr_sq)

Ausgabe:

[ 1  9 25 49]

Beispielcodes: numpy.square() mit komplexen Zahlen

import numpy as np

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

arr_sq = np.square(arr)

print(arr_sq)

Ausgabe:

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