np.square: How to Calculate Square of Numpy Array

The square() method in Numpy returns an array of squared elements.

np.square

The np.square() method is used to find the square of every element in a given array. The numpy square() method takes four parameters: arr, out, where, and dtype, and returns a new array with an argument value as the square of the source array elements.

To find the square of an array, you can use the numpy square() method. The source array remains unchanged. The np square() is a utility function to get the matrix elements’ square quickly.

Syntax

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

Parameters

arr: Input array_like containing the elements to be squared.

out : (ndarray, None, or tuple of ndarray) [Optional parameter] It specifies an alternate output array in which the resulting product is placed. This must have the same or broadcastable shape as the expected output.

where : (array_like) [Optional parameter] These are the elements to be included.

dtype : [Optional parameter] It specifies the type of the returned array. 

Return Value

The square of each of the items in the passed array is in the form of an array.

np.square in Python

Note

  • If the input array is blank, the square() method returns an empty array.
  • This method can show a parabolic plot of the square function.

Examples

The following example demonstrates the use of the square() method.

import numpy as np

arr1 = [1, 2, 3, 4, 5]
arr2 = np.square(arr1)
print(arr2)

Output

[ 1  4  9 16 25]

Numpy square() floating-point array

Let’s take a numpy array with floating-point values.

import numpy as np

arr1 = [1.1, 2.1, 1.9, 4.6]
arr2 = np.square(arr1)
print(arr2)

Output

[ 1.21  4.41  3.61 21.16]

Now, let’s take two integers and two float values and see the output.

import numpy as np

arr1 = [1.1, 21, 19, 4.6]
arr2 = np.square(arr1)
print(arr2)

Output

[  1.21 441.   361.    21.16]

Numpy square for complex numbers

To find the square of complete numbers, use the np.square() method.

The following code demonstrates the case where an array element is a complex number.

import numpy as np

arr1 = [2 + 4j]
arr2 = np.square(arr1)
print(arr2)

Output

[-12.+16.j]

The parabolic plot of the square function

The following example demonstrates the parabolic plot of the square function.

For this example, you have to install the matplotlib library. If you have not installed it, then please first install it.

Now, see the following code.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(start=-100, stop=100, num=100, endpoint=True)

plt.title("Green : Squared values\nOrange : Linear plot")
plt.plot(x, np.square(x), color='green')

plt.plot(x, x, color='orange')
plt.show()

Output

Numpy square Example

You can see the Parabolic graph of the square() method in Numpy.

Pass an empty array

If we pass an empty array to the np.square() function, it will return the empty array.

The following example demonstrates the case where an empty array is passed.

import numpy as np

arr1 = []
arr2 = np.square(arr1)
print(arr2)

Output

[]

The following example demonstrates the use of the where parameter to specify which elements to square. For the remaining items, garbage value gets returned.

import numpy as np

arr1 = [1, 2, 3, 4, 5]
arr2 = np.square(arr1, where=[True, False, True, False, True])
print(arr2)

Output

[                   1 -4611677251740556998                    9
      140266991895344                   25]

From the output, you can see that it returns garbage values for the remaining elements.

Specifying the dtype

The following example demonstrates the case where dtype is to specify the data type of the elements.

import numpy as np

arr1 = [5, 2, 1]
arr2 = np.square(arr1, dtype=np.int8)
print(arr2.dtype == np.int8)

arr1 = np.array([5, 2, 1], dtype=np.int8)
print(np.square(arr1).dtype == np.int)
print(np.square(arr1).dtype == np.int8)

Output

True
False
True

In the above code, we have defined a data type of arr2 to int8.

The following example demonstrates the application of this method in a simple programming context.

Given a sequence of numbers, find the sum of their squares.

import numpy as np

n = int(input("Count: "))
numbers = []

for i in range(n):
    numbers.append(int(input()))

numbers = np.square(numbers)
res = sum(numbers)

print(res)

Output

Test Case 1:
->python3 example7.py
Count: 4
1
2
3
4
30

Test Case 2:
->python3 example7.py
Count: 3
1
2
3
14
 

In this example, we have taken two test cases to demonstrate the sum and square of the numbers.

We have used the functions like int(), input(), range(), append(), square(), and sum() functions.

That is it for the numpy square() method.

See also

Numpy divide()

Numpy diag()

Numpy diag_indices()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.