Let us explore this function further.
Function Syntax
Despite its simplistic operation, the function supports various parameter values as expressed in the syntax below:
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:
- x – refers to the input array.
- 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 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:
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.
print(f"absolute array: {np.absolute(arr_2)}")
This should return:
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.
print(f"absolute array: {np.absolute(arr_3)}")
This should return:
Matplotlib Visualization
We can visualize absolute values using matplotlib, as shown in the code snippet below.
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!!