w3resource

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


2. Ufunc: Square Root Calculation

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to use the np.sqrt ufunc on a 2D array and then filter out any non-real results.
  • Write a Numpy program to compute the square roots of elements in a 2D array and then compare the results with element-wise exponentiation.
  • Write a Numpy program to apply np.sqrt on a 2D array with embedded negative values using a custom error handling routine.
  • Write a Numpy program to combine np.sqrt with np.where to conditionally compute square roots only for positive elements in a 2D array.

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.



Follow us on Facebook and Twitter for latest update.