JacquesC wrote: ↑Mon Jul 20, 2020 3:36 am
It is not a very important problem but just a question if somebody have some ideas about the different result beetween microPython an Python when I calculate 1 - 1/3 ?
MicroPython uses whatever the native float implementation is for the hardware it's running on. On ESP32 that's single-precision floating point. CPython on your PC is using double-precision. As with base-10, 1/3 and 2/3 cannot be exactly represented in floating point.
MicroPython on Linux uses double-precision and agrees with CPython
Code: Select all
>>> 1-1/3
0.6666666666666668
>>> 2/3
0.6666666666666666
>>> 2/3 > ( 1-1/3 )
False
(As does MicroPython on a Pyboard D SF6, which also uses double-precision)
In general, the advice for using floating point numbers (in any language) is to never rely on exact comparison of two floating point values. In your example from CPython, the fact that you got the "correct" result of False was kind of an accident because of the way the precision errors worked out.
Python (and MicroPython) provide math.isclose for exactly this reason --
https://docs.python.org/3/library/math. ... th.isclose
So instead of writing:
it should be
(This doesn't happen automatically because it's slower and for most purposes the distinction doesn't matter)