RBM
RBM

Reputation: 73

Read float wrong value from txt file c++

I have a text file of values:

133.25 129.40 41.69 2.915

when I read it:

fscanf(File, "%f", &floatNumber[i]);

I get these values:

1.3325000000000000e+002, 1.2939999389648437e+002, 4.1689998626708984e+001 2.9149999618530273e+000

the first value is okay but the other three values why they are different?

Upvotes: 2

Views: 1570

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

The reason the values are different is that all numbers except the first one cannot be represented exactly as a binary float value. If you need exact representation of decimals, you need to use a non-standard library.

Upvotes: 1

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

Although most of your inputs cannot be represented exactly in either format, you would have got a lot more matching digits using double rather than float.

I regard float as a very specialized type. If you have a very large array of low precision floating point data, and are doing only very well behaved calculations on it, you may be able to gain some performance by using float. You get twice as many floats in e.g. a cache line. For anything else, prefer double to float.

Upvotes: 0

Srikant Krishna
Srikant Krishna

Reputation: 881

The values are the same, you need to change the format specificier in your printf.

Also, floating point numbers have discrete precision, it is therefore not possible to reprenent any arbitrary floating point numbers to infinite accuracy.

This is well-known problem with IEEE spec.

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385264

They're not different. Floating-point is only accurate to a point [sic]. These are the closest representations of those values. Floating-point is a special beast.

Upvotes: 1

Related Questions