Python NumPy square() Function

  • Post author:
  • Post category:NumPy / Python
  • Post last modified:November 27, 2023
  • Reading time:18 mins read

In NumPy, the square() function is used to compute the element-wise square of each element in an input array. It returns a new array with the squares of the original elements. The function is part of the NumPy mathematical functions and is particularly useful for operations where you need to square each element in an array.

In other words, this mathematical function helps to user calculate the square values of every element in the given array. The NumPy square() function 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. In this article, I will explain how to use Numpy square() function on single and multi-dimension arrays.

1. Quick Examples of NumPy square() Function

If you are in a hurry, below are some quick examples of how to use Python NumPy square() function.


# Quick examples of numpy square() function

# Example 1: Use numpy.square() function 
# To get single element
arr = 25
arr2 = np.square(arr)

# Example 2: Use numpy.square() function
arr = [2, 3, 5, 8, 9, 4]
arr2 = np.square(arr)

# Example 3: Use numpy.square() function 
# To floating-point array
arr = [2.3, 3.5, 5.1, 8.7, 9.2, 4.8]
arr2 = np.square(arr)

# Example 4: Use numpy.square() function 
# With negative numbers
arr = [-6, -13, -25, -8, -15, -17]
arr2 = np.square(arr)

# Example 5: Use numpy.square() function 
# To square from multiple array
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6]])
arr2 = np.square(arr)

# Example 6: Use numpy.square() function 
# with complex numbers
arr = [2+3j, -4-5j, 3-4j, -3+4j]
arr2 = np.square(arr)

# Example 7: Use complex numbers
arr = 6 + 5j
arr2 = np.square(arr)

# Example 8: Use numpy.square() function 
# To graphical representation  
arr = np.linspace(start = -12, stop = 15,num = 6, endpoint = True)
arr2 = np.square(arr)                 
plt.plot(arr, np.square(arr)) 
plt.plot(arr, arr, color = 'yellow')
plt.show()

# Example 9: Use numpy.square() 
# To get the empty array
arr = np.array([])
arr2 = np.square(arr)

2. Syntax of NumPy square()

Following is the syntax of the numpy.square() function.


# Syntax of numpy.square() 
numpy.square(arr, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None)

2.1 Parameters of square()

  • arr – Input array.
  • out – It is ndarray, None, or tuple of ndarray and None, optional. Out will be the location where the result is to be stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly allocated array is returned.
  • where (optional) – A boolean array of the same shape as arr, where an element is squared only if the corresponding value is True. This condition is broadcast over the input.
  • dtype (optional) – The desired data type for the array. If not specified, the data type of arr is used.

2.2 Return Value

It returns an array with square() value of each input array

3. Usage of NumPy square() Function

This mathematical Python NumPy in-built function square() takes the input array as param and returns a square value of each element in the input array. Moreover, you can get the square root values of an array using numpy.sqrt().

3.1 Get the Square Value of Single Element

You can use the numpy.square() function to compute the square value of a single element of an input NumPy array. For instance, first import the NumPy library with the alias np. Creates a NumPy array arr containing a single element, 25. Then you can use np.square() to compute the square of the single element in the array.


# Import numpy
import numpy as np

# Create input array
arr = np.array([25])
print("Original array:",arr)

# Use numpy.square() 
# To get the square value
arr2 = np.square(arr)
print("Square value:",arr2)

Yields below output.

numpy square

3.2 Get the Square Values of Multiple Elements of 1-D Array

If you want to get the square values of multiple elements in a 1-D array using NumPy. You can calculate the square values of integer array elements by using the numpy.square() function.

In the below example, to create a 1-D NumPy array arr with elements [2, 3, 5, 8, 9, 4], then use np.square() to compute the square of each element in the array. Finally, it prints both the original array and the resulting array with squared values.


# Create an 1D input array
arr = [2, 3, 5, 8, 9, 4]
print("Original array:",arr)

# Use numpy.square() function
# To get the square value
arr2 = np.square(arr)
print("Square values:",arr2)

Yields below output.

numpy square

4. Get the Square Values of Float Elements of 1-D NumPy Array

If you have a 1-D NumPy array with floating-point elements and you want to get the square values of those elements. For instance, arr is a 1-D NumPy array with float elements [2.3, 3.5, 5.1, 8.7, 9.2, 4.8]. The np.square() function is then used to compute the square of each element in the array.


# Creating an 1D input array
arr = [2.3, 3.5, 5.1, 8.7, 9.2, 4.8]
print("Original array:",arr)

# Use numpy.square() function 
# To get the square values of floating point
arr2 = np.square(arr)
print("Square values:",arr2)

# Output:
# Original array: [2.3, 3.5, 5.1, 8.7, 9.2, 4.8]
# Square values: [ 5.29 12.25 26.01 75.69 84.64 23.04]

5. Get the Square Values of Negative Elements

You can also calculate the square values of the negative numbers using the numpy.square() function. To get the square values of negative elements in a NumPy array, For example, arr is a 1-D NumPy array with negative elements [-6, -13, -25, -8, -15, -17]. The np.square() function is used to compute the square of each element in the array.


# Creating an 1D input array
arr = [-6, -13, -25, -8, -15, -17]
print("Original array:",arr)

# Use numpy.square() function 
# With negative numbers
arr2 = np.square(arr)
print("Square values:",arr2)

# Output:
# Original array: [-6, -13, -25, -8, -15, -17]
# Square values: [ 36 169 625  64 225 289]

6. Get the Square Values of 2-D NumPy Array Elements

If you want to get square values of 2-dimensional array elements you will use square() function of NumPy array. It will give the square values of 2-D array elements. Let’s create a 2-D NumPy array using numpy.array().


# Creating an 2D input array
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6]])

# Use numpy.square() function 
# Get the square values of 2-D array elements
arr2 = np.square(arr)
print("Square values of 2D array:\n",arr2)

# Output:
# Square values of 2D array:
# [[25 64  9 49]
# [81 16  4 36]]

7. Get the Square Values of Complex Numbers

If you have a NumPy array containing complex numbers and you want to get the square values of those complex numbers, you can use the numpy.square() function.

In the below example, arr is a 1-D NumPy array with complex numbers. The np.square() function is then used to compute the square of each complex number in the array.


# Create an array with complex values
arr = [2+3j, -4-5j, 3-4j, -3+4j]

# Use numpy.square() function 
# With complex numbers
arr2 = np.square(arr)
print("Square values:\n",arr2)

# Output :
# Square values:
#  [-5.+12.j -9.+40.j -7.-24.j -7.-24.j]

8. Get the Square Values on Graphical Representation

You can also use NumPy square() function for graphical representation using MatLab library.


import numpy as np
import matplotlib.pyplot as plt
 
# Use numpy.square() function to graphical representation  
arr = np.linspace(start = -12, stop = 15,
                num = 6, endpoint = True)

arr2 = np.square(arr)                 
print(arr2)

plt.plot(arr, np.square(arr)) 
plt.plot(arr, arr, color = 'yellow')
plt.show()

# Output:
# [144.    43.56   1.44  17.64  92.16 225.  ]
numpy square

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

9. Get The Empty Array

To create an empty NumPy array using np.array([]) and then apply the np.square() function to it. However, it’s important to note that an empty array, in this context, refers to an array with zero elements.

In this case, np.square() is applied to each element of the empty array, resulting in another empty array. The squaring operation doesn’t change the fact that the array is empty.


# Create an empty array
arr = np.array([])

# Use numpy.square() 
# To get the empty array
arr2 = np.square(arr)
print("Square empty array:\n",arr2)

# Output: 
# Square empty array:
#  []

Frequently Asked Questions

What does numpy.square() do?

The numpy.square() function is a NumPy mathematical function that is used to compute the element-wise square of each element in a given array. It takes an array as input and returns a new array where each element is the square of the corresponding element in the input array.

Can numpy.square() handle arrays with different data types?

numpy.square() is designed to work with arrays of different data types, including integers, floats, and complex numbers.

Can numpy.square() handle complex numbers?

numpy.square() can handle complex numbers. When applied to an array containing complex numbers, it computes the square of each complex number, which involves squaring both the real and imaginary parts.

What happens if the input array is empty?

If the input array passed to numpy.square() is empty, the function will return an empty array as well. The resulting array will have the same shape as the input array, which, in the case of an empty array, means it will also be empty.

How does numpy.square() handle negative values?

numpy.square() handles negative values by squaring each element independently, without considering the sign. When you square a negative number, the result is positive.

Can I use numpy.square() with mathematical expressions?

You can use numpy.square() with arrays resulting from mathematical expressions. The function operates element-wise on the input array, so any array resulting from a mathematical expression can be squared using numpy.square()

Conclusion

In this article, I have explained how to use Python NumPy.square() function using how to calculate the square value of every element in the given array with examples.

Happy Learning!!

References

Malli

Malli is an experienced technical writer with a passion for translating complex Python concepts into clear, concise, and user-friendly articles. Over the years, he has written hundreds of articles in Pandas, NumPy, Python, and takes pride in ability to bridge the gap between technical experts and end-users.

Leave a Reply