OK, the pow10round() function I gave earlier seems more "natural" to me, but this should do what you want:
Code:
from math import floor, log
def pow_round(x):
return 10**(floor(log(x,10)-log(0.5,10)))
Here it is in action:
Code:
>>> from math import floor, log
>>>
>>> def pow_round(x):
... return 10**(floor(log(x,10)-log(0.5,10)))
...
>>> pow_round(1)
1.0
>>> pow_round(4)
1.0
>>> pow_round(5)
10.0
>>> pow_round(4.99)
1.0
>>> pow_round(9.99)
10.0
>>> pow_round(10.01)
10.0
>>> pow_round(49.99)
10.0
>>> pow_round(50)
10.0
>>> pow_round(50.001)
100.0
>>> pow_round(500.001)
1000.0
>>> pow_round(499.99)
100.0
>>> pow_round(0.3)
0.10000000000000001
>>> pow_round(0.5)
1.0
>>> pow_round(0.99)
1.0
>>> pow_round(0.004)
0.001
>>>
The discrepancy at values that are exactly at the midpoint of a range (e.g. 0.5, 5, 50, etc.) is likely the result of floating point imprecision.
Bookmarks