Quote:
Originally posted by vinay_s_s
can anyone tell me why 0.7 is stored as 0.699999 ???
|
This is because computers store numbers in
binary using only two digitis: 0 and 1. So a computer has to store a number in powers of two: 0, 1, 2, 4, 8, 16, 32,...
A human usually "store" numbers in
decimal using 10 digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. We humans store (write down) a number in powers of ten.
For example "zero" point "eight" "one" "two" "five" is written down by humans as:
0.8125. The part after the dot actually means: 8/10 + 1/100 + 2/1000 + 5/10000 (note the powers-of-10 pattern: 10, 100, 1000, 10000)
The same number is stored by a computer (using only 0 and 1 digits) as 0.1101.
The part after the dot means: 1/2 + 1/4 + 0/8 + 1/16 (note the powers-of-2 pattern: 2, 4, 8, 16)
Now the number of this example could be written down (stored)
exactly in 5 digits in both decimal and binary form. But try a number very simple for humans like 1/10. We write the value down as "0.1" which is exactly the value 1/10. The very same
exact value in binary is: "0.000110011". So humans write 1/10 down in only two digits, computers need ten digits.
Float and double type var's store floating point numbers, but with a fixed number of bytes. In Linux on a x86 a float is 4 bytes and a double is 8. This limits the precision.
Your number 0.7 is 0.10110011 exactly in binary. That would seem to fit in 4 bytes, but a float should also be able to store numbers like 324.7e+11, so much of the four bytes is taken to store the integer part (here 324) and the exponent (here 11). So only part of the 4 bytes are available for storing the fraction (the part after the dot). Your 0.7 didn't fit in, and using powers of two 0.6999 was as close as it could get to 0.7