Remainders with fractional divisions not working in Python. For example,

>>> 59.28%3.12
3.119999999999999
>>> 59.28/3.12
19.0

Is there any way to get 0.0 as the output of 59.28%3.12

有帮助吗?

解决方案

I don't know why, I don't know details of modulo implementation for floats, however this works fine:

from decimal import Decimal
Decimal("59.28") % Decimal("3.12")

EDIT: Note that you have to use quotes " (i.e. strings) in constructors. Otherwise it will try to interpret both numbers as floats which is the source of the problem (incorrect approximation).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top