-4

I am wondering if it is possible that the following C program prints something else then 0?

double f(double x, double y) {
  return x*x/x+x*x*x; // or whatever operations using *, /, +, -
}
int main(int argc, char** argv) {
  double x = 4.0;
  double y = 5.0;
  double z = f(x,y);
  x += 1e-7;
  x -= 1e-7;
  printf("%f\n", (f(x,y+1e-7)-z)/1e-7);      
  return 0;
}

Can anyone enlighten me regarding this? Cheers,

melpomene
  • 84,125
  • 8
  • 85
  • 148
syl
  • 41
  • 5

2 Answers2

1

If x must be four, then no, because adding 1e-7 to x and then subtracting it again does not change x, when using 64-bit IEEE 754 binary floating-point arithmetic. That means the same two values of x will be passed to the two calls to f, so the same result will be returned, and their difference will be zero.

If x can be changed, then you can get a non-zero value with by setting x to 0x3.ffffffffffff8p0 and by changing the statement in f to:

return x*x*x*x*x*x;
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

Disregarding your comment "// or whatever operations using *, /, +, -", you function f completely ignores y, and uses only x to return x+x^3. Tracing your code:

z = x + x^3
f(x, y+1e-7) is also x+x^3, hence equal to z.

Finally you are printing

(f(x, y+1e-7) - z) / 1e-7

Since we established f(x, y+1e-7) is equal to z, you are doing (z-z)/1e-7. By definition, 0 divided by any number is 0.

Note that since both numbers were reached in idential manner, you don't even have a chance for any floating point fun either (one of the rare cases where two floating numbers are actually equal). Hence for the code you have you can get non-zero print unless you have some hardware or compiler, or ... bug.

Virtually Real
  • 1,572
  • 4
  • 16
  • 20
  • 1
    This assumes that `f(x,y+1e-7)` uses the same value of `x` as the earlier `f(x,y)`. However, the two statements `x += 1e-7;` and `x -= 1e-7;` do not always leave `x` at its original value, if we allow that `x` may be something other than the `4.0` shown in the sample code. – Eric Postpischil Dec 13 '12 at 21:47