SoNoob
SoNoob

Reputation: 33

adding and subtracting values in C

I got the following exam question in a test exam, and would appreciate if someone could help with an explanation of the following question.

Consider the following piece of code:

double a = 1.0, b = 1.0, c = 1.0e-16;
a += c;
a -= c;
b -= c;
b += c;

What are the Values of a and b?.

A: a and b are both equal to 1:0.

B: a is equal to 1:0 and b is less than 1:0.

C: a is less than 1:0 and b is equal to 1:0.

D: a is less than 1:0 and b is less than 1:0.

Upvotes: 1

Views: 119

Answers (1)

interjay
interjay

Reputation: 110069

First of all, the exact behavior and accuracy of floating-point numbers is not defined by the C standard. If we assume IEEE-754 double-precision floating point numbers, then the following can be said:

DBL_EPSILON (about 2.2e-16) is defined as the difference between 1 and the next greater representable number. This means that if you add at least DBL_EPSILON / 2 to 1.0, the result will be closer to 1.0 + DBL_EPSILON than to 1.0 so the result will not be 1.0. For your code, c is less than DBL_EPSILON / 2, so 1.0 + c gives 1.0.

(Note: I assume here that the rounding mode is to round to the nearest number, which is the default on most implementations. Other rounding modes can give different results).

When you go below a power of two (such as 1.0), the density of floating-point numbers doubles. This means that the effective value of epsilon drops to half its value. So DBL_EPSILON / 4 would be the minimum value that, when subtracted from 1.0, will give a different result. Since c > DBL_EPSILON / 4, 1.0 - c gives a different result.

The result of this is that the first addition to a will have no effect but the subtraction will change it, so it will end up with a value less than 1. b will be affected by both operations and end up equal to 1.0.

This is verified by trying it out, giving:

a=0.99999999999999988898 b=1.00000000000000000000

Upvotes: 5

Related Questions