我有一个可以具有任意精度的浮点,并且指示该数字的最小值的最小步长可以通过以下方式增加/减少:
num = 3.56891211101
min_step = 0.005
我想要一个函数,它取这个num
和step_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 上
大多数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
我用解决了这个问题
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
希望它对别人有帮助。