Floating point limitations

29 views
Skip to first unread message

Jesse Hoobergs

unread,
Mar 8, 2024, 10:19:36 AMMar 8
to Skulpt
Hi

When I run the following code in python, is gives me
0.30000000000000004 due to floating point limitations. In Skulpt, however, it just shows 0.3.

burger = 0.1
drink = 0.2
total = burger + drink
print(total)

Why is this? Is this by design, or a bug?

Pascal G

unread,
May 11, 2024, 9:37:20 AMMay 11
to Skulpt

In JavaScript and many other languages, numbers are represented as a mantissa multiplied by an exponent.
Numbers are stored with this amount of bits: 
* Sign bit: 1 bit
* Mantissa (Significand): 52 bits
* Exponent: 11 bits
The mantissa can store a number from 0 to 2^52 = 4503599627370495
This is a 15 and a half digits number.
Any error after the 15th digit is normal and expected.
There is no bug as such here. 


Jesse Hoobergs

unread,
May 11, 2024, 11:06:57 AMMay 11
to Skulpt
I'm sorry, my question might have been a bit unclear.

I know how floating point numbers work, my questions was, why does Skulpt not behave as floating point numbers do?

Python gives me the long 0.30...4 answer, but Skulpt gives 0.3.

I found (but forgot to post it here) that Skulpt seems to round to 12 digits (https://github.com/skulpt/skulpt/blob/master/src/float.js#L603).

Why is this rounding added?

Op zaterdag 11 mei 2024 om 15:37:20 UTC+2 schreef paga...@gmail.com:

jeff.s...@gmail.com

unread,
May 11, 2024, 10:04:23 PMMay 11
to Skulpt
jesse.h...@kuleuven.be, your question is very clear.  You are correct that 0.30000000000000004 is the best answer that 52-bit binary floating point can produce.  This confuses many people.  Floating point behavior isn't widely understood, even among programmers who haven't studied how floats are implemented.  This leads to constant complaints and error reports about "wrong answers".

I can't answer your question.  But I can supply a bit of perspective.

Many language implementations have dealt with floating point resolution by rounding printed values to N digits so that they "look better".  There were even debates and code changes about this in the history of Python.

Floating point is hard.  Do you want to satisfy computer nerds by printing the most accurate answers possible?  Then don't round.  Do you want to reduce complaints and error reports from end users who are troubled to see "wrong" answers?  Then round to N digits when printing values.  I imagine that Skulpt has chosen the latter approach.  This looks like an area where Skulpt differs from the Python reference implementation.
Reply all
Reply to author
Forward
0 new messages