What is the numpy.absolute() Method

Numpy.absolute() method is “used to calculate the absolute value of each element.”

Syntax

numpy.absolute(arr, out = None, ufunc ‘absolute’)

Parameters

The absolute() function can take up to three parameters:

  1. arr: The input array or object whose absolute value needs to be calculated.
  2. out: This is an optional field. A position the product is stored in. When given, it must have a form on which the inputs communicate. If not provided or None, it returns a freshly allocated list. A tuple must have a length equal to the number of outputs (possible only as a keyword argument).

Return Value

The absolute() function returns the array containing the absolute value of the given array or object.

Example 1: How to Use np.absolute() Method

import numpy as np

# Creating one 1D array
arr1 = [12, -5, -14, -100]

# printing its absolute values
print("Absolute values of arr1 are: ", np.absolute(arr1))

# Creating 2D array
arr2 = [[14, -4, 12], [-100, -3, 1]]

# printing its absolute values
print("Absolute values of arr1 are:\n ", np.absolute(arr2))

Output

Absolute values of arr1 are: [ 12 5 14 100]
Absolute values of arr1 are:
 [[ 14 4 12]
 [100 3 1]]

Example 2: Absolute value of equations

import numpy as np

# creating object

eq = (5-14)
# printing its absolute values
print("Absolute values of the equation is : ", np.absolute(eq))

eq2 = 10-100

# printing its absolute values
print("Absolute values of the equation is : ", np.absolute(eq2))

Output

Absolute values of the equation is : 9
Absolute values of the equation is : 90

Example 3: Plotting the absolute value

import numpy as np
import matplotlib.pyplot as plt

# Giving values of point to be plotted
a = np.linspace(start=-10, stop=10, num=100)

plt.title("Blue:with absolute\nGreen:without absolute")

# Ploting values with absolute values
plt.plot(a, np.absolute(a))

# Ploting values without absolute valuess
plt.plot(a, a, color='green')
plt.show()

Output

Python NumPy absolute() Function

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.