Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading