meow
meow

Reputation: 307

Subtraction of Double type Values in C++

I am trying to subtract a small double number from a large double number in C++. Here is my code

int main() 
{
double a=166666166667000000.000000;
double b=1.0;
double c=4.0;
double d=10.0;

double ans_b=a-b;
double ans_c=a-c;
double ans_d=a-d;

printf("%f\n%f\n%f\n",ans_b,ans_c,ans_d);
return 0;
}

This Code is giving me following output -

166666166667000000.000000
166666166667000000.000000
166666166667000000.000000

However, all three are supposed to be different. Why does subtraction with double type behaves this way?

Upvotes: 1

Views: 4665

Answers (1)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

166666166667000000 and 10 are both exactly representable in double. The real number arithmetic result of the subtraction, 166666166666999990, is not. The largest double that is strictly less than 166666166667000000 is 166666166666999968.

166666166666999990 is closer to 166666166667000000 than to 166666166666999968, so 166666166667000000 is the round-to-nearest double result of the subtraction.

If you are just doing the one small number subtraction, you can ignore the issue. If you are doing enough small number subtracts that their cumulative effect matters, you need to rearrange your calculation.

Upvotes: 1

Related Questions