Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to round to arbitrary precision in Python [closed]

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!

like image 394
RolfBly Avatar asked Oct 25 '13 21:10

RolfBly


People also ask

How do you round accurately in Python?

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.

How do you round off without using the round function in Python?

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.

How do you round off 0.5 in Python?

We can add 0.5 to the value which is shifted and then round it down with the math. floor() function.

How do you round to 2 decimal places in Python?

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.


1 Answers

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
like image 92
cmd Avatar answered Oct 24 '22 01:10

cmd