Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8041

MicroPython • Re: int() doing odd things.

$
0
0
This is a complete or consistent problem. Representing floating point is hard.
Accurate representation of some floating numbers is not just hard but impossible, with 0.1 being a well known example of that.

So we have to accept that 0.1 + 0.2 will often give a result of 0.30000000000000004

I don't have a problem with that. The issue IMO comes down to whether str(0.1 + 0.2) should deliver a "0.30000000000000004" or "0.3" result. I believe it should be the first. The first is an accurate representation of what value it actually held, while "0.3" is not.

It seems CPython exhibits similar behaviour so I'd also class that as a bug, funky unexpected behaviour -

Code:

>>> 0.1 + 0.20.30000000000000004

Code:

>>> "{:.64f}".format(0.1 + 0.2).rstrip("0")'0.3000000000000000444089209850062616169452667236328125'
But I guess that lets MicroPython off the hook as only being as broken as CPython, albeit with different outcomes due to the differing bit-sizes of float.

This appears to work for both CPython and MicroPython, delivering what I want to see for 'str()' but not exhaustively tested -

Code:

def FloatToString(f):  s = "{:.64f}".format(f).rstrip("0")  if s.endswith("."):    s += "0"  return sstr = FloatToString
That highlighted a difference between CPython and MicroPython; "{:.128f}" is capped at 64 fractional part digits whereas MicroPython is capped at 19. I guess that is more a feature than a bug providing it is enough to accurately report the smallest non-zero value.

Statistics: Posted by hippy — Mon Apr 28, 2025 7:30 pm



Viewing all articles
Browse latest Browse all 8041

Trending Articles