Python 浮点数可以被另一个浮点数整除

gbt*_*mon 0 python python-2.7

有没有人知道在python中检查一个数字是否可以被python浮点数中的另一个整除的好方法?

我尝试的第一件事是......

3.5 % 0.1 == 0.0
Run Code Online (Sandbox Code Playgroud)

但这又回来了,False所以也许

3.5 % 0.1 >= 1e-6 
Run Code Online (Sandbox Code Playgroud)

但也False......无赖......结果是

3.5 % 0.1
>> 0.099999999924
Run Code Online (Sandbox Code Playgroud)

那么这有效:

LAMBDA = 1e-9
def is_divisible_by(x, y):
   m = x % y
   dy = abs(y - m)
   return m < LAMBDA or dy < LAMBDA

is_divisible_by(3.5, 0.1)
Run Code Online (Sandbox Code Playgroud)

但这似乎很危险,因为我必须选择 LAMBDA。如果y = LAMBDA / 2...

is_divisible_by(LAMBDA/2, (LAMBDA/2) + 1e-10)
>>> True
Run Code Online (Sandbox Code Playgroud)

那么

  def is_divisible_by(x, y):
      l = y * 1e-2
      m = x % y
      dy = abs(y - m)
      return m < l or dy < l

  is_divisible_by(3.5 * 1e-10, 0.1 * 1e-10)
  >>> True

  is_divisible_by(0.21, 0.211)
  >>> True
Run Code Online (Sandbox Code Playgroud)

无赖。

有没有办法解决这个问题,而不会把一只巨大的兔子弄丢?

Pet*_*per 6

根据浮点数的来源,该decimal模块可能有用。

>>> import decimal
>>> decimal.Decimal("3.5") % decimal.Decimal("0.1")
Decimal('0.0')
Run Code Online (Sandbox Code Playgroud)

  • 问题是,如果您的浮点数已经不精确,`decimal.Decimal(str(x))` 就不能重新引入精度。例如:`decimal.Decimal(str(1.0 / 3)) * 3 == 1` 将返回 `False`。 (2认同)