w3resource

NumPy: Calculate the absolute value element-wise


7. Element-wise Absolute Value

Write a NumPy program to calculate the absolute value element-wise.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array with floating-point numbers
x = np.array([-10.2, 122.2, .20])

# Displaying the original array
print("Original array:")
print(x)

# Calculating the element-wise absolute value and displaying the result
print("Element-wise absolute value:")
print(np.absolute(x))

Sample Output:

Original array:                                                        
[ -10.2  122.2    0.2]                                                 
Element-wise absolute value:                                           
[  10.2  122.2    0.2]

Explanation:

In the above code:

x = np.array([-10.2, 122.2, .20]) – This line creates an array with three elements: -10.2, 122.2, and .20.

np.absolute(x) – This line calculates the absolute value of each element in x.

Finally, the result printed by print(np.absolute(x)) will be [10.2, 122.2, .2].

Pictorial Presentation:

NumPy Mathematics: Calculate the absolute value element-wise.

For more Practice: Solve these Related Problems:

  • Implement a function that returns the absolute value of each element in an array using np.abs.
  • Test the absolute value function on arrays containing both negative and positive numbers.
  • Verify the function’s behavior on complex numbers by comparing np.abs with manual magnitude calculations.
  • Apply the absolute value computation to a multi-dimensional array and confirm that its shape remains unchanged.

Python-Numpy Code Editor:

Previous: Write a NumPy program to get the element-wise remainder of an array of division.
Next: Write a NumPy program to round array elements to the given number of decimals.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.