w3resource

NumPy: Round array elements to the given number of decimals

NumPy Mathematics: Exercise-8 with Solution

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:

Previous: Write a NumPy program to calculate the absolute value element-wise.
Next: Write a NumPy program to round elements of the array to the nearest integer.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-8.php