Kodeclik Blog
numpy.round()
Assume you have a numpy array of temperatures, like so:
import numpy as np
temperatures = np.array([65.812,70.354,72.311,75.517,82.325])
print(temperatures)
The output will be:
[65.812 70.354 72.311 75.517 82.325]
numpy.round() is a handy function to round all elements of the array.
We use numpy.round() like so:
print(np.round(temperatures))
The output will be:
[66. 70. 72. 76. 82.]
Note that 65.812 has been rounded (up) to 66 and 70.354 has been rounded (down) to 70. By default numpy.round() rounds to zero decimal places. If we wish to retain some decimal places, we specify it with an argument, like so:
print(np.round(temperatures,decimals=2))
The output now will be:
[65.81 70.35 72.31 75.52 82.32]
Note that 75.517 which previously was rounded (up) to 76 is now rounded (down) to 75.52 because we asked for two decimal places and this was the rounding operation performed at that decimal level. Similarly, if we do:
print(np.round(temperatures,decimals=1))
we get:
[65.8 70.4 72.3 75.5 82.3]
(You can convince yourself that they are correct.) Note that if we used “decimals=3” that will essentially be the same as not doing any rounding at all, because all entries already have 3 decimal places.
print(np.round(temperatures,decimals=3))
The output will be:
[65.812 70.354 72.311 75.517 82.325]
Thus numpy.round() enables us to round numbers to a specific number of decimal places or significant figures. This can be especially helpful when dealing with large numbers and need them rounded off properly for consistency. We can apply this function first before doing any further operations.
For more Python content, checkout the math.ceil() and math.floor() functions! Also
learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.