Need help with micro:bit math

Hello,

I have a student who encountered something odd in MakeCode. The student set a variable to 16.9 at program start. Then “On Shake” change the variable by -1.3. However then the variable is displaying as 15.599999999 instead of 15.6. Tried changing input to “On Tilt” or “On Button A Press” with same results. Tried setting variable to different numbers like 17.9 or 18.9 with similar results. However for some reason setting variable to 14.9 and subtracting 1.3 did indeed equal 13.6.

Any ideas what is happening?

Thanks

That’s because it’s a floating point number.

Computers only have so many bytes that they can use for each number they store. To make the numbers fit in that limited space, they store an approximation instead of the actual value. 99.9% of the time this isn’t a problem, because being .0000000001 off from the actual number is an acceptable amount of error. It does look confusing when you print it out, though!

1 Like