How does Micropython avoid double precision issues?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
alidayvn
Posts: 4
Joined: Fri Aug 30, 2019 8:34 am

How does Micropython avoid double precision issues?

Post by alidayvn » Wed Oct 09, 2019 9:39 am

After implementing doubles, I wanted to test double equality. But to my surprise, 0.1+0.2==0.3 returns True instead of False, although on my PC, Python3 does return False.

I also tried 0.1+0.2-0.3, which returns 5.551115123125783e-17 on my PC, but 0.0 on Micropython.

I thought avoiding double precision issues was only possible with BCD, but from what I've seen, Micropython floats are plain old IEEE754 floats.

- How does Micropython avoid these kinds of double precision issues?
- Is there an operation where a BCD system (used by TI/casio calculators) would return a different answer from Micropython?

stijn
Posts: 362
Joined: Thu Apr 24, 2014 9:13 am

Re: How does Micropython avoid double precision issues?

Post by stijn » Wed Oct 09, 2019 10:21 am

There is no way to avoid those issues, it's inherent to using floating point numbers. And yes it's possible different implementations will return different answers. As such you should probably never compare floating point numbers using ==, if you need to compare them you should use math.isclose or similar.

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

Re: How does Micropython avoid double precision issues?

Post by jimmo » Wed Oct 09, 2019 10:40 am

In the specific example of 0.1+0.2==0.3, this is True on single-precision STM32, and False on double-precision STM32 and the (also double-precision) Unix port.

Post Reply