سؤال

I just want to show you the results of the operations in python. I cannot explain.

>>> 1.0%1.0
0.0  (OK)
>>> 1.0%0.1
0.09999.... 
>>> 1.0%0.001
0.00999....
>>> 1.0 %0.0001
0.000999...

... and so on. I need something that allows me to understand whether the remainder of 'x%y' is 0.0, namely 'y' divides 'x' exactly N times, where N is an integer. Due to the previous behavior I don't know how to set a possible tolerance to determine if the remainder is next to 0. Any help?

هل كانت مفيدة؟

المحلول

As this (long) response says, use decimal module:

>>> from decimal import Decimal
>>> Decimal('3.5') % Decimal('0.1')
Decimal('0.0')
>>> print(Decimal('3.5') % Decimal('0.1'))
0.0
>>> (Decimal(7)/2) % (Decimal(1)/10)
Decimal('0.0')

The problem is essentially due to the representation of floats in the system, you can read stuff about that everywhere on the Internet, and in the response linked.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top