# Rounding error when casting double to short

• 10-23-2006
thetinman
Rounding error when casting double to short
I have a mathematical problem with C. For some reason the variables x and y in the code below are not exactly equal all of the time. I believe that the problem has to do with casting. How, exactly do I cast the equations for x and y so that they are always equal?

Code:

```long x, y, w; double a, b; x = a*w/b+0.5;```
• 10-23-2006
Tonto
What conditions make these not equal? Does it have to do with overflow?
• 10-23-2006
thetinman
I edited the first post. I misunderstood my problem. I still suspect though that I have a problem with casting.

regarding your post. My variables are b = 350, 3 < a < 500, and 10 < w < 200,000.
• 10-23-2006
QuestionC
Sorry, but there's really nothing you can do.

double and float are just approximations, so most mathematical truisms don't apply.

Case in point:
Code:

```#include <iostream> int main (void) {         double a = 9.95;         double b = 1;         long x;         x = a/b + .05;         std::cout << x << '\n'; // 9         a *= 10;         b *= 10;         x = a/b + .05;         std::cout << x << '\n'; // 10         return 0; }```
• 10-24-2006
SKeane
Both are 10 with your code compiled with gcc on a 32-bit machine.
• 10-24-2006
Dave_Sinkula
Quote:

Originally Posted by SKeane
Both are 10 with your code compiled with gcc on a 32-bit machine.

Except where they aren't both 10 on a 32-bit machine compiled with gcc in either C (with necessary modifications) or C++.
• 10-24-2006
QuestionC
Quote:

Originally Posted by SKeane
Both are 10 with your code compiled with gcc on a 32-bit machine.

Your mileage may vary. Optomization, for example, will change the results. Typically, (int) (9.95 + 0.05) == 9 is a really safe bet.
• 10-25-2006
swoopy
Quote:

Originally Posted by QuestionC
Your mileage may vary. Optomization, for example, will change the results. Typically, (int) (9.95 + 0.05) == 9 is a really safe bet.

Funny, I get 10.000000.