# Thread: Rounding error when casting double to short

1. ## 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;```

2. What conditions make these not equal? Does it have to do with overflow?

3. 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.

4. 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;
}```

5. Both are 10 with your code compiled with gcc on a 32-bit machine.

6. 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++.

7. 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.

8. 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.