Efficient way to round to arbitrary precision in Python

What is the Pythonic solution for the next?

I am reading a temperature sensor with a resolution of .5. I need to write (it has a programmable thermostat output), also with a resolution of .5.

So, I wrote this function (Python 2.7) to round a float as input to the nearest .5:

def point5res(number): decimals = number - int(number) roundnum = round(number, 0) return roundnum + .5 if .25 <= decimals < .75 else roundnum print point5res (6.123) print point5res(6.25) print point5res(6.8) 

Which works great, outputs 6.0, 6.5 and 7.0, respectively. This is what I want.

I am relatively new to Python. Line

 return roundnum + .5 if .25 <= decimals < .75 else roundnum 

makes me drool with admiration for its developers. But is it Pythonic?

Edit: after posting, I learned a little more about what it is and is not "Pythonic" . My code is not. Cmd, below, is. Thanks!

+6
source share
2 answers

They are considered pythonic if you keep simple expressions, otherwise it becomes difficult to read.

I would round to the nearest 0.5, like this:

 round(number*2) / 2.0 

or more general:

 def roundres(num, res): return round(num / res) * res 
+6
source
 return 0.5 * divmod (number, 0.5) [0] if number >= 0 else -0.5 divmod (number, -0.5) [0] 

It looks nicer though:

 def roundToHalf (number): ''' Round to nearest half ''' half = 0.5 if number >= 0 else -0.5 return half * divmod (number, half) [0] 
0
source

Source: https://habr.com/ru/post/956756/


All Articles