w3resource logo
Python Exercises

Python NumPy: Round elements of the array to the nearest integer

Python NumPy Math, Statistics, Trigonometry and Linear algebra: Exercise-9 with Solution

Write a Python program to round elements of the array to the nearest integer.

Sample Solution:-

Python Code:

import numpy as np
x = np.array([-.7, -1.5, -1.7, 0.3, 1.5, 1.8, 2.0])
print("Original array:")
print(x)
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.]

Python Code Editor:

Improve this sample solution and post your code through Disqus