Tutorials  /  Python

NumPy sqrt() in Python - Tutorial

Ccentron Redaktion · March 2024 ·2 min read ·Python, Tutorial

Contents

  1. Python NumPy sqrt() Example
  2. NumPy sqrt() Infinity Example
  3. Complex Numbers
  4. Negative Numbers

Python NumPy module is used to work with multidimensional arrays and matrix manipulations. We can use NumPy sqrt() function to get the square root of the matrix elements.

Python NumPy sqrt() Example

Python
import numpy

array_2d = numpy.array([[1, 4], [9, 16]], dtype=numpy.float)

print(array_2d)

array_2d_sqrt = numpy.sqrt(array_2d)

print(array_2d_sqrt)

Output:

[[ 1.  4.]
 [ 9. 16.]]
[[1. 2.]
 [3. 4.]]

Let’s look at another example where the matrix elements are not square of integers. This time we will use the Python interpreter.

Code
>>> import numpy
>>> 
>>> array = numpy.array([[1, 3], [5, 7]], dtype=numpy.float)
>>> 
>>> print(array)
[[1. 3.]
 [5. 7.]]
>>> 
>>> array_sqrt = numpy.sqrt(array)
>>> 
>>> print(array_sqrt)
[[1.         1.73205081]
 [2.23606798 2.64575131]]
>>> 
VM

Matching infrastructure at centron

Scripts and services eventually need an environment that keeps running: ccloud³ VMs from €4.04 per month, billed by the hour. Rent a cloud server →

NumPy sqrt() Infinity Example

Let’s see what happens when we have infinity as the matrix element.

Code
>>> array = numpy.array([1, numpy.inf])
>>> 
>>> numpy.sqrt(array)
array([ 1., inf])
>>> 

Complex Numbers

Code
>>> array = numpy.array([1 + 2j, -3 + 4j], dtype=numpy.complex)
>>> 
>>> numpy.sqrt(array)
array([1.27201965+0.78615138j, 1.        +2.j        ])
>>> 

Negative Numbers

Code
>>> array = numpy.array([4, -4])
>>> 
>>> numpy.sqrt(array)
__main__:1: RuntimeWarning: invalid value encountered in sqrt
array([ 2., nan])
>>> 

The square root of a matrix with negative numbers will throw RuntimeWarning and the square root of the element is returned as nan.

Claim €200 credit

Test your setup on ccloud³

Sign up for ccloud³ and receive €200 starting credit for your project.

centron Redaktion Technical editorial team

The centron editorial team writes guides from day-to-day operations: tested on our own platform, run in our data centre in Hallstadt near Bamberg.

Category Python
Share
Still have questions?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

Was this tutorial helpful?

Your answer is stored anonymously and helps us improve our tutorials.

Comments

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Get started for free

Sign up and receive €200 credit at centron within your first 60 days.

This promotional offer applies to new accounts only. Available exclusively to businesses.