Re: Wrong float to double conversion in VC++ 2005
Rahul wrote:
On Sep 5, 6:09 pm, "Igor Tandetnik" <itandet...@mvps.org> wrote:
"Rahul" <rahulsha...@lucent.com> wrote in message
news:137cb68d-a377-4750-9d64-4f12b6e26d6f@t1g2000pra.googlegroups.com
I have following code
void fun(float f) // f has a value -201.99992 (VC++ debugger shows
this)
double yi = y; // Now the yi value becomes -201.99992370605469
instead of -201.99992000000000
Similarly to how 1/3 is not exactly representable as a finite decimal
fraction, -201.99992000000000 is not exactly representable as a
finite binary fraction (which is how floating point values are
represented internally).
So I tried the following
float f = -201.99992f;
double d1 = -201.99992;
double d2 = -201.99992f;
double d3 = f;
cout<<setw(35)<<setprecision(25)
<<"\n"<<d1 // Prints -201.99992
<<"\n"<<d2 // Prints -201.99992370605469
<<"\n"<<d3; // Prints -201.99992370605469
The printed value of d1 shows that -201.99992 is representable fully
as a double,
No, it's not. It's just close enough that rounding to 17 significant digits
came out with "the right answer".
So here I guess -201.99992 is not exactly representable
as a "float". So the float might be stored as with value something
like -201.99991 etc. in memory? (please correct me if I am wrong)
Now my question is -> When -201.99991 gets converted to double then
the compiler can simple append 0 in the end and make it
-201.99991000000000,
Why does it puts those random integers?
They're not at all random...
Any clarification on the same?
When you widen a float to a double, you get the double value that's as close
as possible to the actual float value, not the double that's as close as
possible to the value of the float rounded to some number of decimal places.
For IEEE 754 floating point, which is what all PCs use, you're guaranteed to
get a double with exactly the same value as the float. The difference
you're seeing is simply a matter of how many digits after the decimal place
are produced by default when you convert a float to a string as opposed to
converting a double to a string.
If you want to understand this stuff, read this paper:
http://www.physics.ohio-state.edu/~dws/grouplinks/floating_point_math.pdf
-cd