w3resource

NumPy: Round array elements to the given number of decimals


Write a NumPy program to round array elements to the given number of decimals.

Sample Solution:-

Python Code:

# Importing the NumPy library
import numpy as np

# Rounding the numbers to the nearest integer
x = np.round([1.45, 1.50, 1.55])
print(x)

# Rounding the numbers to one decimal place
x = np.round([0.28, .50, .64], decimals=1)
print(x)

# Rounding the numbers to the nearest even value
x = np.round([.5, 1.5, 2.5, 3.5, 4.5])
print(x) 

Sample Output:

[ 1.  2.  2.]                                                          
[ 0.3  0.5  0.6]                                                       
[ 0.  2.  2.  4.  4.]

Explanation:

x = np.round([1.45, 1.50, 1.55]) – This code rounds the values in the list [1.45, 1.50, 1.55] to the nearest integer using the np.round function. The output would be [1., 2., 2.].

x = np.round([0.28, .50, .64], decimals=1) – This code rounds the values in the list [0.28, 0.50, 0.64] to one decimal place using the np.round function with the decimals argument set to 1. The output would be [0.3, 0.5, 0.6].

x = np.round([.5, 1.5, 2.5, 3.5, 4.5]) – This code rounds the values in the list [0.5, 1.5, 2.5, 3.5, 4.5] to the nearest even integer using the np.round function. This is called "round to nearest, ties to even". The output would be [0., 2., 2., 4., 4.].

Pictorial Presentation:

NumPy Mathematics: Round array elements to the given number of decimals.

Python-Numpy Code Editor: