Remainder on Float in Python [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-12 05:15:22

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35529398/floating-point-arithmetic-and-numpy-remainder-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!