Python Numpy.sqrt() - Square Root

In this tutorial, we will learn how to get the square root of an array using the numpy.sqrt() function in Python.

 

numpy.sqrt() Syntax

The sqrt() function takes the input array as the first argument and an optional out key.

 

result = numpy.sqrt(array[, out=None])

 

  • result – the output array containing square roots of the original values.
  • array – the array of numerical values to use.
  • out – an optional array to store the output in. Must be the same shape as the original array.

 

Get Square Root of Array Elements

Let's import NumPy and get the square root of each element in an array.

 

import numpy

array = [4, 9, 25]

result = numpy.sqrt(array)

print(result)
[2. 3. 5.]

 

numpy.sqrt() using the out Parameter

Here is another example, this time with the out parameter defined.

 

import numpy

array = [4, 9, 25]
out_array = numpy.zeros(3)

result = numpy.sqrt(array, out_array)

print(result)
print(out_array)
[2. 3. 5.]
[2. 3. 5.]

 

A mentioned earlier, out must be exactly the same shape as the input array or you will get a ValueError.

 

import numpy

array = [4, 9, 25]
out_array = numpy.zeros(4)

result = numpy.sqrt(array, out_array)

print(result)
print(out_array)
ValueError: operands could not be broadcast together with shapes (3,) (4,)
numpy