NumPy: Round elements of the array to the nearest integer
NumPy Mathematics: Exercise-9 with Solution
Write a NumPy program to round elements of the array to the nearest integer.
Sample Solution:-
Python Code:
# Importing the NumPy library
import numpy as np
# Creating an array with float values
x = np.array([-.7, -1.5, -1.7, 0.3, 1.5, 1.8, 2.0])
# Displaying the original array
print("Original array:")
print(x)
# Rounding elements of the array to the nearest integer
x = np.rint(x)
print("Round elements of the array to the nearest integer:")
print(x)
Sample Output:
Original array: [-0.7 -1.5 -1.7 0.3 1.5 1.8 2. ] Round elements of the array to the nearest integer: [-1. -2. -2. 0. 2. 2. 2.]
Explanation:
numpy.rint function is used to round elements of the array to the nearest integer. The values are rounded to the nearest integer.
In the above exercise, the original x array has the values [-0.7, -1.5, -1.7, 0.3, 1.5, 1.8, 2.0]. After applying np.rint(x), the new array will have the values [-1., -2., -2., 0., 2., 2., 2.].
Python-Numpy Code Editor:
Previous: Write a NumPy program to round array elements to the given number of decimals.
Next: Write a NumPy program to get the floor, ceiling and truncated values of the elements of an numpy array.
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://www.w3resource.com/python-exercises/numpy/python-numpy-math-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics