Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

My PC doesn't know how to multiply doubles?

Status
Not open for further replies.

timmay3141

Programmer
Dec 3, 2002
468
US
This is probably the strangest problem I've ever had with C++. I'm multiplying the same two doubles in two different places in the program, using the exact same line of code, and they are giving different values. The values I'm multiplying are 50.0 exactly and 0.001 exactly (I know they are exactly these because I am checking them with the debugger). The first time I multiply them, I get 0.050000000745058 every time I run the program. The second time I multiply them (in another function), I get 0.05 exactly every time I run the program. How is this possible? Is there anything I can do to fix it? Kinda confused here...
 
Hmm, perhaps there is a slight change that your debugger will only show up to three decimals? Have you gotten it to show more in the past?

-Bones
 
The way you know that they're exact is by dumping out the 8 bytes which make up a double. Most decimal output routines suppress the noise which is in the least significant bits of floating point numbers.
Code:
{
  unsigned long temp[2];
  memmove( temp, &mydouble, sizeof temp);
  cout << &quot;Double = &quot; << mydouble;
  cout << &quot;hex = &quot; << hex << temp[0] << &quot; &quot; << temp[1];
}
This will print all the bits used to store a double, and you'll see that some of them are different.

Any serious use of floats should be preceded by reading this

--
 
Fascinating reference, Salem, Thanks!

An interesting indication that what you see in decimals is not what the computer sees:
open excel and make a column nice and wide.
Enter the number 1, and set the number format to print it to 30 decimal places.
Now divide it by 3.
You should get 0.33333.... for about 15 decimal places, followed by zeroes.
Now enter in the next cell down, exactly the same number.
Now multiply both by 3.
One will be 1.00000 etc. (to as many dp as you want)
the other will be 0.99999 etc. (to 15 dp)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top