What is a Pythonic solution to the following?
I'm reading a temperature sensor that has .5 resolution. I need to write to it (it has a programmable thermostat output), also with .5 resolution.
So I wrote this function (Python 2.7) to round off a float as input to the 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 fine, outputs 6.0, 6.5 and 7.0, respectively. That's just what I want.
I'm relatively new to Python. The line
return roundnum + .5 if .25 <= decimals < .75 else roundnum
has me drooling with admiration for it implementors. But is it Pythonic?
Edit: since posting, I have learned a little more about what is and isn't 'Pythonic'. My code isn't. Cmd's anwwer, below, is. Thank you!
Rounding up using round() The first approach anyone uses to round numbers in Python is the built-in round function – round(n, i). It takes two values as arguments; the number “n” that is to be rounded off and “i,” the number of decimal places the number needs to be rounded off to.
Answer: To round up or down without the built-in round(), we first multiply the number to be rounded by 10.0n, where n is the decimal place to keep. Then, we use math. trunc() for truncation, math. ceil() for rounding up or math.
We can add 0.5 to the value which is shifted and then round it down with the math. floor() function.
Python's round() function requires two arguments. First is the number to be rounded. Second argument decides the number of decimal places to which it is rounded. To round the number to 2 decimals, give second argument as 2.
They are considered pythonic if you keep the expressions simple otherwise it becomes difficult to read.
I would round to the nearest 0.5 like this:
round(number*2) / 2.0
or more generically:
def roundres(num, res):
return round(num / res) * res
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With