comparison 1-1/3 <> 2/3 microPython VS Python 3.7

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
JacquesC
Posts: 16
Joined: Sun Feb 17, 2019 5:04 am

comparison 1-1/3 <> 2/3 microPython VS Python 3.7

Post by JacquesC » Mon Jul 20, 2020 3:36 am

Hello,
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 ?

Code: Select all

MicroPython v1.12-120-g4ab8bee82 on 2020-02-02; ESP32 module with ESP32
Type "help()" for more information.
>>> 1 - 1/3
0.6666666
>>> 2/3
0.6666667
>>> 2/3 > ( 1-1/3 )
True

Code: Select all

Python 3.7.2 (/usr/local/bin/python3.7)
>>> 1 - 1/3
0.6666666666666667
>>> 2/3
0.6666666666666666
>>> 2/3 > ( 1-1/3 )
False
Thank you
Jacques

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: comparison 1-1/3 <> 2/3 microPython VS Python 3.7

Post by jimmo » Mon Jul 20, 2020 4:01 am

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:

Code: Select all

a > b
it should be

Code: Select all

not math.isclose(a, b) and a > b
(This doesn't happen automatically because it's slower and for most purposes the distinction doesn't matter)

User avatar
JacquesC
Posts: 16
Joined: Sun Feb 17, 2019 5:04 am

Re: comparison 1-1/3 <> 2/3 microPython VS Python 3.7

Post by JacquesC » Mon Jul 20, 2020 4:18 am

Thank you Jimmo,
it is what I was looking for and you have confirmed what I was thinking.

If I ask thoses questions it is because I am preparing courses for my students and I know that they wil ask me why ;)
The difference beetween precision with floating point is OK for me but why is there a difference in logic expressions ?

Post Reply