Calculate the absolute value of float values in Numpy


To return the absolute value of float values, use the numpy.fabs() method in Python Numpy. This function returns the absolute values (positive magnitude) of the data in x. Complex values are not handled, use absolute to find the absolute values of complex data.

The out is 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.

Steps

At first, import the required library −

import numpy as np

Create an array with float type using the array() method −

arr = np.array([76.7, 28.5, 91.4, -100.8, -120.2, 150.4, 200.7])

Display the array −

print("Array...
", arr)

Get the type of the array −

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

Get the dimensions of the Array −

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

Get the shape of the Array −

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

To return the absolute value of float values, use the numpy.fabs() method in Python Numpy −

print("
Result...
",np.fabs(arr))

Example

import numpy as np

# Create an array with float type using the array() method
arr = np.array([76.7, 28.5, 91.4, -100.8, -120.2, 150.4, 200.7])

# Display the array
print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimension...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # To return the absolute value of float values, use the numpy.fabs() method in Python Numpy print("
Result...
",np.fabs(arr))

Output

Array...
[ 76.7 28.5 91.4 -100.8 -120.2 150.4 200.7]

Our Array type...
float64

Our Array Dimension...
1

Our Array Shape...
(7,)

Result...
[ 76.7 28.5 91.4 100.8 120.2 150.4 200.7]

Updated on: 08-Feb-2022

503 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements