Search code examples
cmathsqrt

Why is this C expression yielding the wrong answer?


I have the following code:

double e = 36858.767828375385;
double c = 2;
double d = 67.877433500000009;

e = sqrt(e / (c * (c - 1))) / d;

The resulting value of e is 2, according to the debugger, but it should be 2.8284271. What am I doing wrong?


Solution

  • The reason e takes the value 2 is because that's the actual answer:

    sqrt(e / (c * (c-1))) / d;

    = sqrt(e / (2 * (2 - 1))) / d

    = sqrt(e / 2) / d

    = sqrt(36858.767828375385 / 2) / d

    = sqrt(18429.383914188) / d

    = 135.754867 / d

    = 135.754867 / 67.877433500000009

    = 2

    Perhaps you have the wrong formula?

    Hope this helps!