0

When I run this into the compiler:

print (7/3)
print (4/3)
print (7/3-4/3-1)
print ("")
print (5/3)
print (2/3)
print (5/3-2/3-1)

The console outputs:

2.3333333333333335
1.3333333333333333
2.220446049250313e-16

1.6666666666666667
0.6666666666666666
0.0

Why does the compiler round 7/3 to 5 at the 16th digit? Other calculators say 7/3 is just 2.333(repeating 3) Also, why does the compiler round the solution for 5/3 but not 2/3?

Jason
  • 25
  • 1
  • 8
  • 1
    The compiler is not ding much in Python. The *interpreter* does. – Willem Van Onsem Sep 20 '17 at 14:56
  • @WillemVanOnsem: Though in this case those expressions are computed at bytecode generation stage rather than at bytecode interpretation stage, thanks to the peephole optimizer, so arguably it _is_ the compiler that's responsible. – Mark Dickinson Sep 20 '17 at 15:33
  • @MarkDickinson: the Python interpreter does close to no optimizations at all. – Willem Van Onsem Sep 20 '17 at 15:34
  • @MarkDickinson: see [here](https://stackoverflow.com/a/38755465/67579). – Willem Van Onsem Sep 20 '17 at 15:36
  • @WillemVanOnsem: As you say, "close to no optimizations", but that's not the same as none. The peephole optimizer does optimize some constant expressions, including the one in the OP. Try `dis.dis(lambda: 7/3-4/3-1)` at a Python 3 prompt to see the generated bytecode. – Mark Dickinson Sep 20 '17 at 15:38
  • @WillemVanOnsem: see [here](https://github.com/python/cpython/blob/36ff451ebae41f09560bff582c95946474d898f8/Python/peephole.c#L232). – Mark Dickinson Sep 20 '17 at 15:42

0 Answers0