Skip to main content
gamedev.net
🔒 Locked

Floatingpoint bug ?

Started by Metzler 2 replies 250+ views
Original Post
Metzler
Metzler
I just found a really strange behaviour with a floating point variable, that is reproducable (at least the misbehaviour itself). I packed the problem into a code snippet :
#include <iostream>
using namespace std;

void main(void)
{
	float test = 0.0;
	for (int i = 0;i < 100; i++)
	{
		test += 0.1;
		cout << test << "\n";
	}
}
[/CODE]

So, when running, it just adds 0.1 to the variable test.
When i look at the output, everything is fine till the value 7.8.
Instead of 7.8 i see 7.79999, 7.89999, 799999, 8.09999
and then it continues the way, it sould be with 8.1, 8.2 and so on ! Why ??? what does this abnormal behaviour mean ??
In the program, where i discovered this bug, the problem starts at 3.1 and doesnt end...

THX for answers     
[edited by - Metzler on September 28, 2002 7:32:31 AM]
Metzler
Metzler
But why cant it represent such an , for us easy example of just adding 0.1 to a number ? I just need one number after the point...

[edited by - Metzler on September 28, 2002 8:43:42 AM]
CWizard
CWizard
Because floats are in this format: 1.m * 2^e
I don't remember exactly, but they are stored in memory similar to this:
[s eeeeeee mmmmmmmm mmmmmmmm mmmmmmmm]
 31-----24 ------16 -------8 -------0

s = the sign (0 = positive, 1 = negative)
e = the power of two
m = mantissa (I think it's called?)

Assuming above format, -2.1 would be translated to: (I use % to prefix binary, don't argue!)
2.0 = %10 = 1.0 * 2^1
0.1 = %0.0001100110011001....

[s eeeeeee mmmmmmmm mmmmmmmm mmmmmmmm]
 1 0000001 00011001 10011001 10011001

You cannot divide a binary number by 10. Think of this: 0x10000 = 65536, 0x10000 / 10 = 0x1999... = 6553,6 = %1100110011001

Sorry for the messy post

[edited by - CWizard on September 28, 2002 9:35:31 AM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.