在Python中,如何将浮点的精度降低到给定的步长?

2024-05-20 15:27:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个可以具有任意精度的浮点,最小步长表示该数字的最小值可以增加/减少:

num = 3.56891211101
min_step = 0.005

我想要一个函数,它接受这个numstep_size,并将num四舍五入到给定的min_step。因此,在这种情况下,结果将是3.570

我试图这样做:

num = 3.56891211101
min_step = 0.005

def myround(x, base):
    return base * round(x / base)

x = myround(num, min_step)
print(x)
>>> 3.5700000000000003

…很近,但不太近。我希望输出与以下情况相同:

y = 3.570
print(y)
>>> 3.57

实现这一点的简单方法是什么

我使用的是Python 3.8


Tags: 函数basesizereturndefstep情况精度
2条回答

我用以下方法解决了这个问题:

def myround(x, base):
    decimal_places = str(base)[::-1].find('.')
    precise = base * round(x / base)
    return round(precise, decimal_places)

x = myround(num, min_step)
print(x)
>>> 3.57

y = 3.570
print(y)
>>> 3.57

希望它对其他人有帮助

大多数Python实现(包括CPython参考实现)都使用IEE 754浮点数。因此,它们对于十进制值不准确

规范的方法是使用十进制模块:

from decimal import Decimal, Context

num = 3.56891211101
c = Context(prec=3)
x= c.create_decimal(num)
print(x)

如期而至

3.57

相关问题 更多 >