如何避免模数浮点数错误?

How to avoid modulus floating point error?

我正在使用取模运算符,但遇到了一些浮点错误。例如,

>>> 7.2%3
1.2000000000000002

我唯一的办法是使用 round 函数来处理这个问题吗?例如

>>> round(7.2%3, 1)
1.2

我事先不知道需要四舍五入的位数,所以我想知道是否有更好的解决方案?

如果你想要任意精度,使用decimal模块:

>>> import decimal
>>> decimal.Decimal('7.2') % decimal.Decimal('3')
Decimal('1.2')

read the documentation carefully.

注意我使用 str 作为 Decimal 的参数。看看如果我不这样做会发生什么:

>>> decimal.Decimal(7.2) % decimal.Decimal(3)
Decimal('1.200000000000000177635683940')
>>>