Read from file -0.000028 and get -2.8000000-e005 WHY!!!

Started by
7 comments, last by papa 19 years, 7 months ago
Hi. I am reading the following data from a text file: "0.000000, -0.000028, 0.912098" this way: if (sscanf(szLine, "%f, %f, %f", &pos.x, &pos.y, &pos.z ) == 3) and what is stored is: x = 0.000000 y = -2.8000000-e005 z= 0.91209799 So. Y is completely wrong and Z slightly wrong it should be 0.912098 in the end rather than 0.91209799. Why is that? It definetely something wrong with the floating point precission but how can I fix this?
Advertisement
Y is not wrong, its mathematically correct if i remember my maths a-level.

-2.8 *10^-5 = -0.000028

as for the Z, make sure you are not confusing floats and doubles anywhere.
No bombs, No guns, just an army of game creators...
First of all y is not wrong, it's just shifted by 5 digits (-e005)

The rest is slightly incorrect because of limited floating point precision, you could perhaps use doubles to get rid of that error.
ok then so what do you do in order to store exactly same number into your data structure as in the text file. I am not using any doubles. All my program is based on floats. Well thats how I contructed my Vector class. Could someone please tell me how to fix this? I dont really wanna start playing with shifting stuff as some of them need that and some dont. There must be a simple way to do that. come on.
Maybve if I read them as doubles and cast to floats? or its even easier solution?
As mentioned before, these two numbers are exactly the same, you don't need to do anything about it, e.g. you can write
y = -0.000028;

or
y = -2.8e-005;

in your program. You don't need to deal with shifting the numbers.
Do you need your number to be exactly the same as they are in the text file? If so, the only way to do that is to use some custom type, likely a fixed point type, that you or someone else has to write.

I would suggest just working with floats, though, because you probably don't need any more accuracy. Besides, even with doubles, you'll still have inaccuracies; they'll just be smaller.

Oh, and read this (from the C++ FAQ Lite).
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
That's the problem with floats. They only have a certain number of bits available to them, so precise floats out to a certain decimal place will be off a little.

Try displaying them with %g instead of %f in your printf.
It's not what you're taught, it's what you learn.
Use %5.5f, it will give you 5 decimals after the decimal point and at most 5 before (it won't padd with 0s like after the decimal point).

You can change the values to anything until it looks ok.
Ok. Thank you all for help. Now I know why :)

This topic is closed to new replies.

Advertisement