Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remainder on Float in Python [duplicate]

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?

like image 318
user3144676 Avatar asked Jan 28 '26 23:01

user3144676


1 Answers

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.

like image 69
Maxime Lorant Avatar answered Jan 30 '26 13:01

Maxime Lorant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!