NumPy sqrt() in Python – Tutorial

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

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.

>>> 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]]
>>> 

NumPy sqrt() Infinity Example

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

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

Complex Numbers

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

Negative Numbers

>>> 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.

Source: digitalocean.com

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in:

Moderne Hosting Services mit Cloud Server, Managed Server und skalierbarem Cloud Hosting für professionelle IT-Infrastrukturen

Cohere Toolkit Installation & Setup on Ubuntu 24.04 | AI & RAG Apps

AI/ML, Tutorial

This guide provides step-by-step instructions for installing and configuring the Cohere Toolkit on Ubuntu 24.04. It includes environment preparation, dependency setup, and key commands to run language models and implement Retrieval-Augmented Generation (RAG) workflows. Ideal for developers building AI applications or integrating large language models into their existing projects.

Moderne Hosting Services mit Cloud Server, Managed Server und skalierbarem Cloud Hosting für professionelle IT-Infrastrukturen

How to Install SonarQube on Ubuntu 24.04 – Step-by-Step Guide

Tutorial, Ubuntu

This tutorial walks through the full installation of SonarQube on Ubuntu 24.04, including system requirements, PostgreSQL setup, and service configuration. You’ll set up SonarQube as a systemd service, connect it to a database, and prepare it for analyzing code in various languages—ideal for integrating quality checks into development pipelines.