Python将浮点数舍入到最接近的0.05

时间:2015-02-10 06:47:51

标签: python

我想模仿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是我最好的选择吗?

3 个答案:

答案 0 :(得分:15)

您可以向下舍入到a的最近倍数:

def round_down(x, a):
    return math.floor(x / a) * a

你可以像这样四舍五入到a的最接近的倍数:

def round_nearest(x, a):
    return round(x / a) * a

答案 1 :(得分:13)

正如@Anonymous所写:

  

您可以舍入到最接近的倍数:

def round_nearest(x, a):
    return round(x / a) * a

工作几乎完美,但round_nearest(1.39, 0.05)给出1.4000000000000001。 为了避免这种情况,我建议你这样做:

import math
def round_nearest(x, a):
    return round(round(x / a) * a, -int(math.floor(math.log10(a))))

具有精确度a

的精确度a,然后是有效位数

答案 2 :(得分:0)

def round_nearest(x,a):
  return round(round(x/a)*a ,2)

这是一个稍微不同的变化!