Kodeclik Blog


Assume you have a numpy array of temperatures, like so:
The output will be:
numpy.round() is a handy function to round all elements of the array.
We use numpy.round() like so:
The output will be:
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:
The output now will be:
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:
we get:
(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.
The output will be:
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.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.