• Post author:
  • Post category:NumPy / Python
  • Post last modified:March 27, 2024
  • Reading time:16 mins read
You are currently viewing Python NumPy Square Root

In Python, NumPy is a powerful library for numerical computing. You can use NumPy to calculate the square root of elements in an array using the numpy.sqrt() function. This function is used to return the non-negative square root of an array element-wise (for each element of the array). In this article, I will explain how to use Numpy square root by using numpy.sqrt() function with examples.

1. Quick Examples of Square Root

If you are in a hurry, below are some quick examples of how to use the Python NumPy square root.


# Quick examples of square root

# Example 1: Use numpy.sqrt() function
# Get single-element
arr = np.array(25)
arr2 = np.sqrt(arr)

# Example 2: Use numpy.sqrt() function 
# Get multiple square root values 
arr =np.array([25, 49, 225, 64, 81, 16])
arr2 = np.sqrt(arr)

# Example 3: Calculate square roots of complex numbers
arr = [2+6j, -5-8j, 4-5j, 3+4j]
arr2 = np.sqrt(arr)

# Example 4: Use numpy.sqrt() function 
# With negative and inifite as input values
arr = [-6, np.inf, 25, -15, np.inf]
arr2 = np.sqrt(arr)

# Example 5: Use numpy.sqrt() function 
# To floating-point array
arr = [4.3, 8.5, 15.1, 23.7, 14.2, 7.8]
arr2 = np.sqrt(arr)

# Example 6: Use numpy.sqrt() function 
# Get the square root values of 2-d array
arr = np.array([[25, 64, 9, 16], [9, 4, 49, 36]])
arr2 = np.sqrt(arr)

2. Syntax of sqrt()

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


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

2.1 Parameters of sqrt()

  • arr – The values whose square roots are required. 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 – It is array_like, optional. This condition is broadcast over the input.

2.2 Return Value

It returns an array of the square root of the number in the input array.

3. Usage of NumPy Square Root Function

You can get the square root of the single element of an array using numpy.sqrt() function. You can also get the square values of the NumPy array using numpy.square().


import numpy as np

# Create a single element
arr = np.array(25)
print("Original array:", arr)

# Use numpy.sqrt() function
# Get single element
arr2 = np.sqrt(arr)
print("After getting the square root value:",arr2)

Yields below output.

numpy square root

4. Get the Multiple Square Root Values

If you want to calculate square roots for multiple values, you can pass a list, tuple, or another array-like object to the numpy.sqrt() function. To initialize the array with list of numbers use numpy.array() and calculate the square root of these numbers by using the numpy.sqrt() function.

In the below example, numpy.sqrt() calculates the square root of each number in the arr list, resulting in [ 5. 7. 15. 8. 9. 4.].


import numpy as np

# Create an input array
arr =np.array([25, 49, 225, 64, 81, 16])
print("Original array:\n",arr)

# Use numpy.sqrt() function 
# Get multiple square root values 
arr2 = np.sqrt(arr)
print("After getting the multiple square root values:\n",arr2)

Yields below output.

numpy square root

5. Get the Square Roots of Complex Numbers

NumPy can handle complex numbers and can calculate square roots of complex numbers using the numpy.sqrt() function. Complex numbers in NumPy are represented using the numpy.complex data type.

In the below example, numpy.sqrt() calculates the square roots of the complex numbers [2+6j, -5-8j, 4-5j, 3+4j]. The result is an array of complex numbers representing the square roots of the input complex numbers.


import numpy as np

# Define complex numbers
arr = np.array([2+6j, -5-8j, 4-5j, 3+4j])
print("Original complex numbers:\n", arr)

# Calculate square roots of complex numbers
arr2 = np.sqrt(arr)
print("After getting the square roots of complex numbers:\n",arr2)

# Output:
# Original complex numbers:
#  [ 2.+6.j -5.-8.j  4.-5.j  3.+4.j]
# After getting the square roots of complex numbers:
#  [2.04016609+1.47046852j 1.4889562 -2.68644571j 2.28069334-1.09615789j
#  2.        +1.j        ]

6. Get The Square Roots of Negative and Infinite Values

Using the numpy.sqrt() function you can also calculate the square root of the negative and Infinite as input values of an array. The square root of a matrix with negative numbers will throw RuntimeWarning and the square root of the element is returned as nan as a result.


import numpy as np

# Create input array
arr =np.array[-6, np.inf, 25, -15, np.inf]

# Use numpy.sqrt() function 
# With negative and infinite 
arr2 = np.sqrt(arr)
print("After getting negative and infinite values:\n",arr2)

# Output:
# [nan inf  5. nan inf]
# RuntimeWarning: invalid value encountered in sqrt

7. Get the Square root of NumPy Array with Float Values

You can calculate the square root of a NumPy array containing float values using the numpy.sqrt() function. For instance, numpy.sqrt() calculates the square root of each element in the arr.


import numpy as np

# Create an 1D input array
arr = np.array( [4.3, 8.5, 15.1, 23.7, 14.2, 7.8])

# Use numpy.sqrt() function 
# To floating-point array
arr2 = np.sqrt(arr)
print("After getting the square roots of float values:\n",arr2)

# Output:
# After getting the square roots of float values:
#  [2.07364414 2.91547595 3.88587185 4.86826458 3.76828874 2.79284801]

8. Get the Square Roots of 2-D NumPy Array Values

You can calculate the square roots of a 2-D NumPy array’s values using the numpy.sqrt() function. For instance, numpy.sqrt() calculates the square roots of each element in the 2-D array, resulting in a new 2-D array where each element is the square root of the corresponding element in the original array. The function performs element-wise square root calculations efficiently on the entire 2-D array.


import numpy as np

# Create an 2D input array
arr = np.array([[25, 64, 9, 16], [9, 4, 49, 36]])

# Use numpy.sqrt() function 
# Get the square root values of 2-d array
arr2 = np.sqrt(arr)
print("After getting the square root 2-D array:\n",arr2)

# Output:
# After getting the square root 2-D array:
#  [[5. 8. 3. 4.]
#  [3. 2. 7. 6.]]

Frequently Asked Questions

What is the purpose of numpy.sqrt() function?

The numpy.sqrt() function in NumPy serves the purpose of computing the square root of each element in a NumPy array. It performs element-wise square root calculations, which means it takes an input array and returns a new array where each element is replaced with its square root.

How can I use numpy.sqrt() to calculate square roots?

You can use numpy.sqrt() by passing a NumPy array as an argument. It will return a new array containing the square root of each element in the input array.

Can I calculate square roots for multi-dimensional arrays?

Using the numpy.sqrt() function can be applied to multi-dimensional arrays, including 2-D arrays. It performs element-wise operations on each element in the array.

How do I handle complex numbers with numpy.sqrt()?

NumPy’s numpy.sqrt() function can handle complex numbers naturally. When you apply numpy.sqrt() to an array that contains complex numbers, it performs the square root operation element-wise, preserving the complex nature of the numbers.

Can numpy.sqrt() handle NaN (Not a Number) values?

numpy.sqrt() can handle NaN (Not a Number) values. When you apply the numpy.sqrt() function to an array that contains NaN values, it calculates the square root element-wise, and if a NaN value is encountered, the result will be NaN as well.

How does numpy.sqrt() handle negative numbers?

You use numpy.sqrt() to calculate the square root of negative numbers, it returns complex numbers. In the context of complex numbers, the square root of a negative number is a complex number with a real part of 0 and an imaginary part corresponding to the positive square root of the absolute value of the input.

Conclusion

In this article, I have explained how to use Python numpy.sqrt() function to calculate the square root 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.