0

I am reading some numbers from a file in C.

For example,

0.00632, 0.02731...

I store these numbers in double type variables.

This is how I read them:

fscanf(fp_ptr, "%lg", &num);

However when I check the value of the num via the watch window of the program I use (Visual Studio Express), I see the values as 0.0063200000000000001, 0.027310000000000001...

Is this normal? How can I read the exact value in the file?

tozak
  • 401
  • 4
  • 12
  • Why is that? Signed bit? – tozak May 10 '14 at 14:50
  • The exact values of the memory variables are 0.006320000000000000096866958898544908151961863040924072265625 and 0.027310000000000000941469124882132746279239654541015625, the closest IEEE 754 64-bit binary numbers to the original decimal fractions. It's just like expressing 1/3 as a decimal fraction with a finite number of decimal places. You would need a decimal or rational data type to represent the inputs exactly. – Patricia Shanahan May 10 '14 at 14:55
  • Yes, it is normal. You might like to read [What Every Programmer Should Know About Floating-Point Arithmetic](http://floating-point-gui.de/). – pmg May 10 '14 at 15:23

1 Answers1

2

You can't store arbitrary values in floating point numbers like double. The ease of computation that comes with standardized floating point numbers is bought at the expense that most numbers simply can't be expressed using this system. This doesnt matter in most cases, since 0.0063200000000000001 is equal to 0.00632 to within fourteen orders of magnitude.

Three possible strategies:

  • Ignore the difference if your values represent values whose precision is allowed to vary. Be aware that differences tend to accumulate.
  • You need a bignum library like GMP if your numbers can be of any arbitrary value and must be precise.
  • If all your values are between 0 and 1 and have only five significant digits (as in your example), you may simply drop the "0." and interpret the rest as an integer value (0.00632 becomes 632, 0.02731 becomes 2731).
user2722968
  • 13,636
  • 2
  • 46
  • 67