-2
>>> print(0.1)
0.1
>>> print(1/10)
0.1
>>> print(1.1 - 1)
0.10000000000000009
>>> print(1.1 % 1)
0.10000000000000009
>>> print(0.05 + 0.05)
0.1

When ideally all of them should output 0.10000000000000009 or something approximate to 0.1 as it cannot be represented precisely as per here

  • 1
    It all depends on how good those true values are represented in floating point. See https://stackoverflow.com/questions/588004/is-floating-point-math-broken for a long and detailed explanation – yatu Sep 09 '20 at 07:52
  • yeah exactly, then why does print(0.1) in python prints the rational 0.1 in place of 0.10000000000000009 – Pranav Singh Sep 09 '20 at 08:35
  • The problem is in representing `1.1` in binary floating point, check the decimal part `1.1%1` – yatu Sep 09 '20 at 08:38
  • i still dont get it, can you give some reference? – Pranav Singh Sep 09 '20 at 08:42
  • 1
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Jongware Sep 09 '20 at 08:49
  • Check out the first link. The problem is that `1.1` can't has this precision in binary floating point `0.10000000000000009`. Hence adding or subtracting `1` to it, which *can* be well represented, will still result in this precision limitation – yatu Sep 09 '20 at 08:50
  • The link explains the binary floating point limitation, which I understand. But then, why does `print(0.1)` or `print(1/10)` gives the exact value instead of the precision limited value when internally, it cannot be represented precisely as it can be seen in `print(1.1-1)` or `print(1.1%1)` – Pranav Singh Sep 09 '20 at 09:13
  • all these should ideally output to 0.1 which can not be represented precisely, so 0.10000000000000009. But why the discrepancy? – Pranav Singh Sep 09 '20 at 09:24

1 Answers1

0

I suggest you print the exact actually represented values to see the differences:

>>> for s in '0.1', '1/10', '1.1', '1.1 - 1', '1.1 % 1', '0.05 + 0.05':
        print(s.rjust(11), ('=> %.70f' % eval(s)).rstrip('0'))

    
        0.1 => 0.1000000000000000055511151231257827021181583404541015625
       1/10 => 0.1000000000000000055511151231257827021181583404541015625
        1.1 => 1.100000000000000088817841970012523233890533447265625
    1.1 - 1 => 0.100000000000000088817841970012523233890533447265625
    1.1 % 1 => 0.100000000000000088817841970012523233890533447265625
0.05 + 0.05 => 0.1000000000000000055511151231257827021181583404541015625

As you see (and should expect), 1.1 has a larger absolute error than 0.1. Subtracting 1 is exact, so the larger absolute error remains.

superb rain
  • 5,300
  • 2
  • 11
  • 25