Python numpy square root

Python NumPy Square Root

Python numpy.sqrt() function is used to return the non-negative square root of an array element-wise (for each element of the array). In this article, I will explain how to use Numpy square root by using numpy.sqrt() function with examples.

1. Quick Examples of Python NumPy Square Root

If you are in a hurry, below are some quick examples of how to use Python NumPy square root function.

 # Below are a quick examples # Example 1: numpy.sqrt() of single element arr2 = np.sqrt(45) # Example 2: Use numpy.sqrt() function to square root of numbers arr = [25, 49, 225, 64, 81, 16] arr2 = np.sqrt(arr) # Example 3: Use numpy.sqrt() function with complex numbers arr = [2+6j, -5-8j, 4-5j, 3+4j] arr2 = np.sqrt(arr) # Example 4: Use numpy.sqrt() function with negative and inifite as input values arr = [-6, np.inf, 25, -15, np.inf] arr2 = np.sqrt(arr) # Example 5: Use numpy.sqrt() function to floating-point array arr = [4.3, 8.5, 15.1, 23.7, 14.2, 7.8] arr2 = np.sqrt(arr) # Example 6: Use numpy.sqrt() function to square root from multiple array arr = np.array([[25, 64, 9, 16], [9, 4, 49, 36]]) arr2 = np.sqrt(arr) 

2. Syntax Python NumPy Square Root

Following is the syntax of the numpy.sqrt() function.

 # Syntax of python numpy.sqrt() numpy.sqrt(arr, out=None, where=True, casting='same_kind', order='K', dtype=None) 

2.1 Parameters of sqrt()

  • arr – The values whose square-roots are required. Input array.
  • out – It is ndarray, None, or tuple of ndarray and None, optional. Out will be the location where the result is to be stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.
  • where – It is array_like, optional. This condition is broadcast over the input.

2.2 Return Value of sqrt()

Return : It returns an array of the square root of the number in the input array.

3. Usage of NumPy Square Root Function

You can get the square root of the single element of an array using numpy.sqrt() function. You can also get the square values of the NumPy array using numpy.square() .

 import numpy as np # Create a single element arr = np.array(25) # Use numpy.sqrt() function to get single element arr2 = np.sqrt(arr) print(arr2) # Output: [5.0] # get single element square root value arr2 = np.sqrt(45) print(arr2) # Output : # 6.708203932499369 

4. Get the Multiple Square Root Values of NumPy Array

To initialize the array with list of numbers use numpy.array() and calculate the square root of these numbers by using the numpy.sqrt() function. For example,

 # Create an input array arr =np.array([25, 49, 225, 64, 81, 16]) # Use numpy.sqrt() function to square root of numbers arr2 = np.sqrt(arr) print(arr2) # Output # [ 5. 7. 15. 8. 9. 4.] 

5. Get the Square Roots of Complex Numbers

You can use complex numbers as elements of an array to calculate the square roots of these elements using numpy.sqrt() . For example,

 # Create an input array arr =np.array( [2+6j, -5-8j, 4-5j, 3+4j]) # Use numpy.sqrt() function with complex numbers arr2 = np.sqrt(arr) print(arr2) # Output # [2.04016609+1.47046852j 1.4889562 -2.68644571j 2.28069334-1.09615789j 2.+1.j ] 

6. Get The Square Roots of Negative and Infinite Values

Using the numpy.sqrt() function you can also calculate the square root of the negative and Infinite as input values of an array. The square root of a matrix with negative numbers will throw RuntimeWarning and the square root of the element is returned as nan as a result.

 # Create an 1D input array arr =np.array[-6, np.inf, 25, -15, np.inf] # Use numpy.sqrt() function with negative and infinite arr2 = np.sqrt(arr) print(arr2) # Output # [nan inf 5. nan inf] # RuntimeWarning: invalid value encountered in sqrt 

7. Get the Square root of NumPy Array with Float Values

You can find the square root of the float values of array elements by using the numpy.sqrt() function.

 # Create an 1D input array arr = np.array( [4.3, 8.5, 15.1, 23.7, 14.2, 7.8]) # Use numpy.sqrt() function to floating-point array arr2 = np.sqrt(arr) print(arr2) # Output # [2.07364414 2.91547595 3.88587185 4.86826458 3.76828874 2.79284801] 

8. Get the Square Roots of 2-D NumPy Array Values

Let’s calculate the square roots 2-D NumPy array values by using numpy.sqrt() function.

 # Create an 2D input array arr = np.array([[25, 64, 9, 16], [9, 4, 49, 36]]) # Use numpy.sqrt() function to get the # square root values of 2-d array arr2 = np.sqrt(arr) print(arr2) # Output # [[5. 8. 3. 4.] # [3. 2. 7. 6.]] 

9. Conclusion

In this article, I have explained how to use Python numpy.sqrt() function to calculate the square root of every element in the given array with examples.

Читайте также:  Сложение разреженных матриц python

References

You may also like reading:

Источник

numpy.sqrt#

Return the non-negative square-root of an array, element-wise.

Parameters : x array_like

The values whose square-roots are required.

out ndarray, None, or tuple of ndarray and None, optional

A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

where array_like, optional

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None , locations within it where the condition is False will remain uninitialized.

For other keyword-only arguments, see the ufunc docs .

Returns : y ndarray

An array of the same shape as x, containing the positive square-root of each element in x. If any element in x is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in x are real, so is y, with negative elements returning nan . If out was provided, y is a reference to it. This is a scalar if x is a scalar.

A version which returns complex numbers when given negative reals. Note that 0.0 and -0.0 are handled differently for complex inputs.

sqrt has–consistent with common convention–as its branch cut the real “interval” [-inf, 0), and is continuous from above on it. A branch cut is a curve in the complex plane across which a given complex function fails to be continuous.

>>> np.sqrt([4, -1, -3+4J]) array([ 2.+0.j, 0.+1.j, 1.+2.j]) 
>>> np.sqrt([4, -1, np.inf]) array([ 2., nan, inf]) 

Источник

Читайте также:  Html в djvu программа

numpy.sqrt#

Return the non-negative square-root of an array, element-wise.

Parameters : x array_like

The values whose square-roots are required.

out ndarray, None, or tuple of ndarray and None, optional

A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

where array_like, optional

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None , locations within it where the condition is False will remain uninitialized.

For other keyword-only arguments, see the ufunc docs .

Returns : y ndarray

An array of the same shape as x, containing the positive square-root of each element in x. If any element in x is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in x are real, so is y, with negative elements returning nan . If out was provided, y is a reference to it. This is a scalar if x is a scalar.

A version which returns complex numbers when given negative reals. Note that 0.0 and -0.0 are handled differently for complex inputs.

sqrt has–consistent with common convention–as its branch cut the real “interval” [-inf, 0), and is continuous from above on it. A branch cut is a curve in the complex plane across which a given complex function fails to be continuous.

>>> np.sqrt([4, -1, -3+4J]) array([ 2.+0.j, 0.+1.j, 1.+2.j]) 
>>> np.sqrt([4, -1, np.inf]) array([ 2., nan, inf]) 

Источник

How to Calculate Square Root using Numpy in Python?

Numpy Sqrt( )

There are many measures in mathematics that intrigue one. One such measure is the square root! While we can readily cry the number out loud when the question is to find the square root for the numbers which are the product of themselves, things take an ugly turn when they no longer comply with the aforementioned condition.

In this article, we would be exploring the different methods of putting into use the in-built function within the numpy library for calculating the square root of the given entities – the sqrt( ) function!

First things first! Import the numpy library before getting on with the deployment of the sqrt( ) function using the below code.

We shall cover the aspects of the sqrt( ) function in the following sections.

  • Syntax of sqrt( ) function
  • Calculating Square Root for One-Dimensional Array
  • Calculating Square Root for N-Dimensional Array
  • Calculating Square Root for Complex Numbers
  • Limitations of sqrt( ) function
Читайте также:  Phpstorm разработка на javascript

Syntax of the sqrt( ) function

Before diving into the details of how to use the sqrt( ) function, let us get started by understanding the basic components that it needs for proper functioning.

numpy.sqrt(x, out=None, where=True, dtype=None)
  • x –input array or scalar entity for which the square root is to be calculated
  • out – an optional construct set to none by default, but could be used to store the results in the desired array which is of the same length as the output
  • where – an optional construct which is used to calculate the universal function (ufunc) at the given position when set to True (default setting) or not calculate when set to False
  • dtype –an optional construct used to specify the data type which is being used

Calculating Square Root for One-Dimensional Array

After importing the numpy library let us construct a one-dimensional array with the elements for which the square root is to be calculated as shown below.

Now let us use the sqrt( ) function to deduce the results for the above array.

Square Root Calculated For One Dimensional Array

Calculating Square Root for N-Dimensional Array:

Similar to one-dimensional arrays, one can also calculate the square root of the given entities grouped together in N-dimensional arrays. Here is a two-dimensional array for which the square root is calculated using the sqrt( ) function as shown below.

ar2 = np.array([[12.5, 33.3, 25], [26, 79, 14.5]], dtype = float) np.sqrt(ar2)

Square Root Calculated For Two Dimensional Array

Calculating Square Root for Complex Numbers

While a straightforward deduction of a square root can give us a run for the money, things get even trickier when we venture into the territory of complex numbers. To put things into perspective, the following is the formula used to calculate the square root of a complex number!

Square Root Formula For Complex Numbers

To save us from misery, the sqrt( ) function also has the capability to deduce the square root of complex numbers too. It has the ability to deduce a complex number directly from the given array, but the flip side to this characteristic is that the function goes on to consider every other element within that array also as a complex number.

ar3 = [[12+5j, 33-3j, 25], [26, 7-9j, 14+5j]] np.sqrt(ar3)

Square Root Calculated For Complex Numbers

Limitations of sqrt( ) function

While it extends its abilities to complex numbers, it is not that the sqrt( ) function is all mighty, rather it also has its limitations too. One such is the disability to calculate the square root for negative numbers.

Let us now attempt to find the square root of ‘-6’ and bear witness to its outcome.

Warning NaN Error Appears

Conclusion

Now that we have reached the end of this article, hope it has elaborated on how to find the square root of array elements using the sqrt( ) function from the numpy library. Here’s another article that explains how to find the maximum amongst a set of array elements using numpy in Python. There are numerous other enjoyable & equally informative articles in AskPython that might be of great help to those who are looking to level up in Python. Whilst you enjoy those, adios!

Источник

Оцените статью