cmathfloating-pointtrigonometry

Incorrect calculation of a math expression using sin and cos in C?


Why does this simple program

#include <stdio.h>
#include <math.h>

int main()
{
    int res = (int)(-1 * sin(M_PI/2) + 1 * cos(M_PI/2));
    printf("-1 * %f + 1 * %f = %d\n", sin(M_PI/2), cos(M_PI/2), res);
    return 0;
}

give the following incorrect output?

-1 * 1.000000 + 1 * 0.000000 = 0

Solution

  • If you print more significant digits:

    double res = -1 * sin(M_PI/2) + 1 * cos(M_PI/2);
    printf("-1 * %.17f + 1 * %.17f = %.17f\n", sin(M_PI/2), cos(M_PI/2), res);
    

    You'll see the problem:

    -1 * 1.00000000000000000 + 1 * 0.00000000000000006 = -0.99999999999999989
    

    The inexact nature of floating point is in this case giving a result for the call to cos that is not exactly 0. So your final result is slightly greater than -1, and converting that value to a int truncates the value toward 0, giving 0 as a result.