我想模仿this function。我想把一个浮点数四舍五入到0.05的最接近倍数(或者通常是任何事物的最接近倍数)。
我要这个:
>>> my_magical_rounding(1.29, 0.05)
1.25
>>> my_magical_rounding(1.30, 0.05)
1.30
我可以做到:
import math
def my_magical_rounding(n, r):
return n - math.fmod(n, r)
>>> my_magical_rounding(1.27, 0.05)
1.25 # Yay!
>>> my_magical_rounding(1.30, 0.05)
1.25 # Boo! I want 1.30.
可能是因为浮点舍入。
我可以做一些特殊的大小写检查,看看n
是否“足够接近”一个r
的倍数,而不是做减法运算,这可能会起作用,但是有更好的方法吗?
或者this strategy是我最好的选择吗?
正如@Anonymous所写:
工作得几乎完美,但是
round_nearest(1.39, 0.05)
给出的结果是1.4000000000000001。 为了避免这种情况,我建议您:精确到
a
,然后精确到有效位数,这就是你的精确值a
这是一个略有不同的变化!
您可以舍入到
a
的最接近倍数,如下所示:您可以按如下方式舍入到
a
的最接近倍数:相关问题 更多 >
编程相关推荐