NumPy square()

The numpy.square() function computes the element-wise square of the input array, returning the squared values of each element.

Syntax

</>
Copy
numpy.square(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)

Parameters

ParameterTypeDescription
xarray_likeInput data whose elements will be squared.
outndarray, None, or tuple of ndarray and None, optionalOptional output array where the result is stored. If None, a new array is created.
wherearray_like, optionalBoolean mask specifying which elements should be squared. Elements where where=False retain their original value.
castingstr, optionalDefines the casting behavior when computing the square function.
orderstr, optionalMemory layout order of the output array.
dtypedata-type, optionalDefines the data type of the output array.
subokbool, optionalDetermines if subclasses of ndarray are preserved in the output.

Return Value

Returns an array containing the element-wise square of the input values. If the input is a scalar, a scalar is returned.


Examples

1. Squaring a Single Value

Here, we compute the square of a single number using numpy.square().

</>
Copy
import numpy as np

# Define a number
num = 5

# Compute the square
result = np.square(num)

# Print the result
print("Square of", num, ":", result)

Output:

Square of 5 : 25