NumPy square()

The square() function computes squares of an array's elements.

Example

import numpy as np

array1 = np.array([1, 2, 3, 4])

# compute the square of array1 values result = np.square(array1)
print(result) # Output : [ 1 4 9 16]

square() Syntax

The syntax of square() is:

numpy.square(array, out = None, where = True, dtype = None)

square() Arguments

The square() function takes following arguments:

  • array1 - the input array
  • out (optional) - the output array where the result will be stored
  • where (optional) - used for conditional replacement of elements in the output array
  • dtype (optional) - data type of the output array

square() Return Value

The square() function returns the array containing the element-wise squares of the input array.


Example 1: Use of out and where in square()

import numpy as np

# Create an array of values
arr = np.array([-2, -1, 0, 1, 2])

# create an empty array of same shape of arr to store the result
result = np.zeros_like(arr)

# compute the square of arr where the values are positive and store the result in result array np.square(arr, where=arr > 0, out=result)
print("Result:", result)

Output

Result: [0 0 0 1 4]

Here,

  • The where argument specifies a condition, arr > 0, which checks if each element in arr is greater than zero .
  • The out argument is set to result which specifies that the result will be stored in the result array.

For any element in arr that is not greater than 0, the corresponding element in result will remain as 0.


Example 2: Use of dtype Argument in square()

import numpy as np

# create an array of values
arr = np.array([1, 2, 3, 4])

# compute the square of arr with different data types result_float = np.square(arr, dtype=np.float32) result_int = np.square(arr, dtype=np.int64)
# print the resulting arrays print("Result with dtype=np.float32:", result_float) print("Result with dtype=np.int64:", result_int)

Output

Result with dtype=np.float32: [ 1.  4.  9. 16.]
Result with dtype=np.int64: [ 1  4  9 16]