NumPy: Calculate the absolute value element-wise
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:
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics