Remains with fractional divisions not working in Python

Remains with fractional divisions not working in Python. For instance,

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

Is there any way to get 0.0 as a result of 59.28% 3.12

+4
source share
1 answer

I don’t know why, I don’t know the details of the modular implementation for float, however this works fine:

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

EDIT: Note that quotes "(i.e. strings) must be used in constructors . Otherwise, he will try to interpret both numbers as floats, which are the source of the problem (incorrect approximation).

+2
source

Source: https://habr.com/ru/post/1535925/


All Articles