fscanf issues

I am reading values from a text files but it prints something different mostly the three numbers changes.
The values of the text file are these
157.029281 9446.924466 6714.689770
but when i run my code it prints this:
157.029282 9446.924805 6714.689941.

This is my code;

float P1[45];
int main()
{
simSP1 = fopen("P1.txt", "r");
fscanf(simP1,"%f%f%f\n",&P1[0],&P1[1],&P1[2]);
printf("%f%f %f\n",P1[0],P1[1],P2[2]);

Any help?

N/B the text file contains 45 different numbers
Single precision floating point simply cannot represent the values {157.029281 9446.924466 6714.689770}

It just can't. The closest it can represent are { 157.0292816162109375 , 9446.9248046875 , 6714.68994140625 } , which are the output numbers you see (suitably rounded).

Read about floating point: http://floating-point-gui.de/

Experiment yourself with what numbers it can represent: http://www.exploringbinary.com/floating-point-converter/

Understand that floating point number cannot represent all decimal values. That there are an infinity of decimal values that floating point cannot represent. Now you know.
There are many base-10 fractional numbers that can't be represented exactly by floating point numbers. For example, on my implementation the closest value I can get for "157.029281" is 157.0292816162109375 using float and 157.029280999999997447957866825163364410400390625 using double.
As you can see, double gets quite a bit closer, but it's not exact. Even a simple number like 0.1 must be approximated with 0.100000001490116119384765625.

You're always going to have these tiny inaccuracies with float. You just have to live with it.
If you definitely need to represent those values exactly, then you need a different representation.
Topic archived. No new replies allowed.