Why does the meaning of this float change from what it was installed on?
Why is this C program giving the "wrong" output?
#include<stdio.h> void main() { float f = 12345.054321; printf("%f", f); getch(); } Output:
12345.054688 But the output should be 12345.054321 .
I am using VC ++ in VS2008.
It gives a “wrong” answer simply because not all real values are represented by floats (or doubled, for that matter). What you get is a base encoding approximation.
To represent any real value, even between 1.0x10 -100 and 1.1x10 -100 (really the minimum range), you still need an infinite number of bits.
IEEE754 unit values have only 32 bits (some of which are set for other things, such as exponents and NaN / Inf representations) and therefore cannot give you infinite accuracy. In fact, they have 23 bits, giving an accuracy of about 2 24 (there is an additional implicit bit) or just over 7 decimal digits (log 10 (2 24 ) is about 7.2).
I will enclose the word “wrong” in quotation marks because this is not entirely wrong. Is your understanding of how computers represent numbers wrong (do not be offended, although you are not alone in this misunderstanding).
Go to http://www.h-schmidt.net/FloatApplet/IEEE754.html and enter your number in the Decimal View box to see this in action.
If you want to get a more accurate number, use doubles instead of float - they have twice the number of bits available for representing values (provided that your C implementation uses IEEE754 of the same type and two-dimensional data types for float and double, respectively).
If you want arbitrary precision, you will need to use a "bignum" library such as GMP , although this is somewhat slower than the native types so make sure you understand the tradeoffs.
The decimal 12345.054321 cannot be represented exactly as a float on your platform. The result you see is a decimal approximation to the nearest number, which can be represented as a float .
float refers to convenience and speed and uses a binary representation - if you need precision, use the decimal type.
To understand the problem, read what every computer scientist needs to know about floating point arithmetic: http://docs.sun.com/source/806-3568/ncg_goldberg.html
For a solution, see frequently asked questions about decimal arithmetic: http://speleotrove.com/decimal/decifaq.html
Single-precision floating point values can contain only eight to nine significant (decimal) digits. In addition, you see a quantization error.
All this is connected with accuracy. Your number cannot be stored exactly in the float.