Python

NumPy.Square

The square function in NumPy allows you to perform an element-wise square of an input array. Once you provide an array, the function will return an array of similar shape with each element in the source array squared.

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:

numpy.square(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'square'>

 
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:

import numpy as np
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.

[[ 400  900 1600]
 [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:

import numpy as np
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:

[[ 4.84 10.89 19.36]
 [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:

import numpy as np
arr = np.array([[-30j, 30j], [-2j, 2j]])
print(np.square(arr))

 
The function returns the square of the provided array as complex numbers.

[[-900.+0.j -900.+0.j]
 [  -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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list