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

2024-10-06 12:00:30 发布

您现在位置: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是我最好的选择吗?


Tags: importreturnmydefmagicalfunctionmaththis
3条回答

正如@Anonymous所写:

You can round to the nearest multiple of a like this:

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

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

这是一个略有不同的变化!

您可以舍入到a的最接近倍数,如下所示:

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

您可以按如下方式舍入到a的最接近倍数:

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

相关问题 更多 >