This function does not perform the operation in-place. Hence, the input array remains unchanged.
Function Syntax
The function syntax is as shown in the following:
The required parameter is x which represents the input array whose elements are what you wish to square.
Example 1: Square Int Array
In the following example, we use the square() function to square the values of an int array:
arr = np.array(
[[20, 30, 40],
[50,60,70]]
)
print(np.square(arr))
The given example returns an array with similar shape with each element of the input array squared.
[2500 3600 4900]]
Example 2: Square Floating-Point Array
You can also perform the square operation on a floating-point array as shown in the following example:
arr = np.array(
[[2.2, 3.3, 4.4],
[5.5,6.6,7.7]]
)
print(np.square(arr))
The resulting array is as follows:
[30.25 43.56 59.29]]
Example 3: Working with Complex Numbers
The square function also allows you to perform the square operations on complex numbers as shown in the following example:
arr = np.array([[-30j, 30j], [-2j, 2j]])
print(np.square(arr))
The function returns the square of the provided array as complex numbers.
[ -4.+0.j -4.+0.j]]
Conclusion
In this brief article, we covered how to use the NumPy square function to get the square of each element in the input array.