Compute the square root of negative input with emath in Python

PythonNumpyServer Side ProgrammingProgramming

To compute the square root of input, use the scimath.sqrt() method in Python Numpy. The method returns the square root of x. If x was a scalar, so is out, otherwise an array is returned. The parameter x is the input value. For negative input elements, a complex value is returned

Steps

At first, import the required libraries −

import numpy as np

Creating a numpy array using the array() method −

arr = np.array([1, -4, -9, 16, -25, 36])

Display the array −

print("Our Array...
",arr)

Check the Dimensions −

print("
Dimensions of our Array...
",arr.ndim)

Get the Datatype −

print("
Datatype of our Array object...
",arr.dtype)

Get the Shape −

print("
Shape of our Array object...
",arr.shape)

To compute the square root of input, use the scimath.sqrt() method in Python Numpy. The method returns the square root of x. If x was a scalar, so is out, otherwise an array is returned −

print("
Result...
",np.emath.sqrt(arr))

Example

import numpy as np

# Creating a numpy array using the array() method
arr = np.array([1, -4, -9, 16, -25, 36])

# Display the array
print("Our Array...
",arr) # Check the Dimensions print("
Dimensions of our Array...
",arr.ndim) # Get the Datatype print("
Datatype of our Array object...
",arr.dtype) # Get the Shape print("
Shape of our Array object...
",arr.shape) # To compute the square root of input, use the scimath.sqrt() method in Python Numpy print("
Result...
",np.emath.sqrt(arr))

Output

Our Array...
[ 1 -4 -9 16 -25 36]

Dimensions of our Array...
1

Datatype of our Array object...
int64

Shape of our Array object...
(6,)

Result...
[1.+0.j 0.+2.j 0.+3.j 4.+0.j 0.+5.j 6.+0.j]
raja
Updated on 01-Mar-2022 07:42:45

Advertisements