// Andrew Taylor - andrewt@unsw.edu.au // // The approximate representation of reals can produce unexpected errors. // If we subtract or divide two values which are very close together // a large relative error can result. // This is called cancellation or catastrophic cancellation. // // if x is close to 0, cos(x) is close to 1 // and calculating 1 - cos(x) can produce a large error in a calculation // // for example below, if x=0.000000011 the correct answer is ~0.5 but we get 0.917540 // // we can avoid the error by replacing 1 - cos(x) with // the mathematically equivalent 2 * sin(x/2) * sin(x/2) // /*``` $ ./a.out Enter x: 0.123 (1 - cos(x)) / (x * x) = 0.499370 (2 * sin(x/2) * sin(x/2)) / (x * x) = 0.499370 $ ./a.out Enter x: 0.000000011 (1 - cos(x)) / (x * x) = 0.917540 (2 * sin(x/2) * sin(x/2)) / (x * x) = 0.500000 ```*/ #include #include int main(void) { double x; printf("Enter x: "); scanf("%lf", &x); printf("(1 - cos(x)) / (x * x) = %lf\n", (1 - cos(x)) / (x * x)); printf("(2 * sin(x/2) * sin(x/2)) / (x * x) = %lf\n", (2 * sin(x/2) * sin(x/2)) / (x * x)); return 0; }