Блог пользователя ibrahim129

Автор ibrahim129, история, 3 года назад, По-английски

I was doing some float operations using python. But when I tried to divide 9999999999999999 by 2 (9999999999999999/2) I got 5000000000000000.0 which is wrong. I already know the issue 8.6-8.4 != 0.2 (issue with binary representation) but I couldn't figure out what is the issue. Can anyone explain this?

  • Проголосовать: нравится
  • +10
  • Проголосовать: не нравится

»
3 года назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

Python float doesnt have enough precision to distinguish a difference at around 1e-16, so in Python, 99...9 (as you wrote) is stored equal to 10...00 (with as many 0s as there were 9s above).

Interactive shell:

Input: float(10000000000000000)==float(9999999999999999)
Output: True
»
3 года назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

You can also use the decimal module in python for accurate floating point arithmetic :

from decimal import Decimal

print(Decimal(9999999999999999)/Decimal(2))