w3resource

NumPy: Round elements of the array to the nearest integer


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: