w3resource

Compute Square Root of each element using np.sqrt in NumPy

NumPy: Universal Functions Exercise-2 with Solution

Using Built-in ufuncs:

Write a NumPy program that uses the np.sqrt ufunc to compute the square root of each element in a 2D NumPy array.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D NumPy array of shape (3, 3) with random integers
array_2d = np.random.randint(1, 100, size=(3, 3))

# Use the np.sqrt ufunc to compute the square root of each element in the array
sqrt_array = np.sqrt(array_2d)

# Print the original array and the resulting array
print('Original 2D array:\n', array_2d)
print('Square root of each element:\n', sqrt_array)

Output:

Original 2D array:
 [[ 4  7 77]
 [69 25 96]
 [29 92  7]]
Square root of each element:
 [[2.         2.64575131 8.77496439]
 [8.30662386 5.         9.79795897]
 [5.38516481 9.59166305 2.64575131]]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create 2D NumPy Array:
    • Create a 2D NumPy array named ‘array_2d’ with random integers ranging from 1 to 99 and a shape of (3, 3).
  • Compute Square Root Using np.sqrt:
    • Used the np.sqrt "ufunc" to compute the square root of each element in the 2D array.
  • Print Results:
    • Print the original 2D array and the resulting array with the square root of each element.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Create a custom ufunc in NumPy to Add 10 to each element.
Next: Add 1D array to each Row of 2D array using np.add in NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/compute-square-root-of-each-element-using-np-dot-sqrt-in-numpy.php