NumPy: Calculate the absolute value element-wise
NumPy Mathematics: Exercise-7 with Solution
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/python-numpy-math-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics