NumPy: Round elements of the array to the nearest integer
9. Nearest Integer Rounding
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.].
For more Practice: Solve these Related Problems:
- Implement a function that rounds elements of a float array to the nearest integer using np.rint.
- Test the function on arrays with both positive and negative values to verify proper rounding behavior.
- Compare the outputs of np.rint, np.floor, and np.ceil for a given array to understand the differences.
- Apply element-wise rounding to a 2D array and confirm that the output retains the original array shape.
Go to:
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.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.