Float bug?

Archives Forums/BlitzPlus Programming/Float bug?

DrMartin(Posted 2004) [#1]
In my game I have a float value that can be changed in the options menu. Depending on what key the user press, the value will be increased or decreased by 0.1.
The problem is that the value sometimes can become 0.999999 or 1.49012e-008.
The only ways I modify this value is "value=value-0.1" and "value=value+0.1". I've added a few lines of code that fixes the problems, but I would really like to know why they show up in the first place.
Has anybody run into anything like this?

Martin Gunnarsson

ashmantle(Posted 2004) [#2]
Thats how floats is supposed to behave.. they're never exacly one number, but float somewhere in close proximity.

Why not use integers?

Storm8191(Posted 2004) [#3]
Martin: if you're only moving your float value by 0.1 and are having issues with accuracy, you can use an integer instead. Just change the value by 1 each time, and when you use it, divide the variable by 10.0 (not just 10, as this will mean it's an integer division and the decimal will be truncated).

DrMartin(Posted 2004) [#4]
Yes, I guess that is a better solution. I absolutely don't agree that this is how floats are supposed to behave. They are *always* exactly one number, but with a bunch of decimals.

Floyd(Posted 2004) [#5]
This really is the way floats work. In this case 0.1 is not exactly representable.
Starting with

x# = 0.1

This tries to assign 0.1 to x. The value 0.1 is displayed by Blitz with Text or Print.
But the display is rounded to six digits. In fact, 0.1 is not the exact value of x.

If you are curious, the exact value of x is 13421773 / 134217728.
The denominator is 2^27. If the denominator could be 134217730 then x would be 0.1 exactly.
But 134217730 is not a power of two, so that can't happen.

So x is 0.1 plus a very small error. When x is repeatedly added to a running total an error is also repeatedly added.
Eventually the total error is large enough to see.

Here's a quick look at the exact value of x.
Graphics 300, 130, 0, 2

x# = 0.1

; Now double it 27 times.

For n = 1 To 27
x = x * 2

Text 20, 40, "Rounded to six digits: " + x
Text 20, 60, "Exact value is really: " + Int(x)

WaitKey : End

DrMartin(Posted 2004) [#6]
Thanks for the explaination, I stand corrected!

WolRon(Posted 2004) [#7]
I think all of this shows why 64bit math would be more useful...

WoeIsMe(Posted 2004) [#8]
V. interesting, Floyd! Heh, a nice little bit of info to remember!

Koriolis(Posted 2004) [#9]
I think all of this shows why 64bit math would be more useful
I don't think so. It would only push the problem further away. You would sitll have problems with 0.999999999, just with more decimals.