-2

Why not 1000 ? The result is float, because of 'Semantics of True Division' in PEP238, but math.float(999.999999999999999) = 1000. That is confusing. I have the assumption, that actually answer is something like 999.9999999123564384, but how to check it? And 10 / .01 = 1000.0 btw.

m9_psy
  • 3,217
  • 5
  • 25
  • 38
  • Because 1/10th cannot be accurately represented in a floating point number. You are not dividing by ten. You are dividing by 10 and a little bit more. – Martijn Pieters Aug 30 '15 at 14:04
  • And [Python math is wrong](http://stackoverflow.com/questions/11950819/python-math-is-wrong) – Bhargav Rao Aug 30 '15 at 14:06
  • Use [`Decimal`](https://docs.python.org/2/library/decimal.html)s if you want that to be true. Floating point is binary. – Dan D. Aug 30 '15 at 14:07
  • Decimal(10) // Decimal(0.01) = Decimal(999) too – m9_psy Aug 30 '15 at 14:09
  • 2
    `Decimal('10')//Decimal('0.01')` --> `Decimal('1000')` – Bhargav Rao Aug 30 '15 at 14:10
  • 1
    You need to pass a string into `Decimal` - `0.01` is the already inaccurate float (the closest float representable value to 1/100), so `Decimal(0.01)` is the Decimal representation of that value. Passing a string lets it see the true base 10 value. – lvc Aug 30 '15 at 14:18
  • This also gives a neat way to see the true value of a float: print the Decimal of it. – lvc Aug 30 '15 at 14:26

1 Answers1

6

0.1 is not exactly one-tenth.

Floating point numbers are binary approximations; just as a decimal number is represented by a sum of 1 + 2 + 4 + 8 + 16, etc, a float is a sum of binary fractions, 1/2 + 1/4 + 1/8 + 1/16, with bits switching on or off each of those fractions in the sum. You can only ever approximate one tenth, but the real value becomes apparent when you format the value with more digits:

>>> format(0.1, '.55f')
'0.1000000000000000055511151231257827021181583404541015625'

That uses the following fractions:

>>> fractions = []
>>> sum = 0.0
>>> for i in range(1, 56):
...     fraction = 2 ** i
...     if sum + (1.0 / fraction) <= 0.1:
...         fractions.append(fraction)
...         sum += 1.0 / fraction
... 
>>> fractions
[16, 32, 256, 512, 4096, 8192, 65536, 131072, 1048576, 2097152, 16777216, 33554432, 268435456, 536870912, 4294967296, 8589934592, 68719476736, 137438953472, 1099511627776, 2199023255552, 17592186044416, 35184372088832, 281474976710656, 562949953421312, 4503599627370496, 9007199254740992, 36028797018963968]

// gives you floor division, and multiplying 1000 by slightly more than 1/10th gives you slightly less than 100, so that is floored to 999.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343