We will discuss the function syntax, parameters, and return value using this tutorial.
NumPy Square() Function Syntax
The function syntax is expressed below:
Function Parameters
The function supports the following parameters:
- x – defines the input array or an array-like object
- where – the condition that is broadcasted over the input array
- casting – defines the casting type
- dtype – the data type of the output array
Function Return Value
The function returns a new array with the elements as the square of each component in the input array.
Since the function creates a new array, it does not alter the original array.
Examples:
Let us illustrate how to use the NumPy square function with practical examples.
Squaring a 1D Array
To square a one-dimensional array, apply the following code:
import numpy as np
arr = [29, 34, 22, 100, 40, 3, 2]
print(f"square array: {np.square(arr)}")
The previous code takes each element in the input array and returns an array with their respective squares.
Note: The resulting array is of the same shape as the input array, as shown below:
Squaring a 2D Array
The same case applies to a two-dimensional array. An example of the code snippet is as shown:
print(f"Squared array: {np.square(arr_2d)}")
The following is the resulting output:
[10000 1600 9]]
Squaring Floating-Point Values
The operation does not change when working with floats.
print(f"Squared array: {np.square(arr_floats)}")
The previous operation returns to the following array:
[106.09 16. 9.61]]
NOTE: If you include an integer in an array containing floating-point values, its resulting square will be a float.
Squaring Complex Numbers
You can also use complex numbers with the square function. Take a look at the example below:
print(f"Squared array: {np.square(arr_complex)}")
This returns to the following array:
[-100.+0.j -16.+0.j 16.+0.j]]
NOTE: Similarly, an integer in an array containing complex numbers is converted to a complex number.
Conclusion
Thank you for reading through this tutorial where we discussed how to use the NumPy square function by understanding the function parameters and return value, along with illustrations of practical examples. Read more related articles at Linux Hint website.