| by Arround The Web | No comments

NumPy np.absolute()

The absolute() function in NumPy allows you to determine the distance between an element and 0, also known as an absolute value in a given array.

Let us explore this function further.

Function Syntax

Despite its simplistic operation, the function supports various parameter values as expressed in the syntax below:

numpy.absolute(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'absolute'>

Parameters

In most cases, you will rarely need to concern yourself with most of the parameters in the function syntax.

The most common parameters are discussed below:

  1. x – refers to the input array.
  2. Out – provides an alternative array to store the output values.

Return Value

The absolute() function will return an array with the absolute value of each element in the input array. The resulting array will hold the same shape as the input array.

Example 1

The following example shows how the function operates on a 1D array.

# import numpy
import numpy as np
arr = np.array([1, -9, 13, -24])
print(f"absolute array: {np.absolute(arr)}")

We start by importing the NumPy package with an alias as np in the code above.

We then create an array using the np.array function. Finally, we return an array containing the absolute values of each element in the arr variable.

The resulting output is as shown:

absolute array: [ 1  9 13 24]

NOTE: The absolute value is always positive.

Example 2 – Floats

Let us see what happens when applying the absolute function to an array of floating-point values.

arr_2 = np.array([1.3, -9.9, 13.2, -24])
print(f"absolute array: {np.absolute(arr_2)}")

This should return:

absolute array: [ 1.3  9.9 13.2 24. ]

The input data type is conserved for the output array. If there is an integer in the array, it is automatically converted to a float.

Example 3 – Complex Numbers

What happens when we apply the function to an array of complex numbers? Let’s find out.

arr_3 = np.array([1.3j, -9.9, 13j, -24])
print(f"absolute array: {np.absolute(arr_3)}")

This should return:

absolute array: [ 1.3  9.9 1324. ]

Matplotlib Visualization

We can visualize absolute values using matplotlib, as shown in the code snippet below.

# import matplotlib
import matplotlib.pyplot as plt
arr = np.linspace(start=-5, stop=5, num=50)
plt.plot(arr, np.absolute(arr))

The code above should return:

Conclusion

This article gives a detailed explanation of the absolute() function in NumPy. We also provide examples and illustrations to portray how the function works.

Thanks for reading!!

Share Button

Source: linuxhint.com

Leave a Reply