sin, cos, tan and rounding error

前端 未结 9 632
执念已碎
执念已碎 2020-12-06 14:09

I\'m doing some trigonometry calculations in C/C++ and am running into problems with rounding errors. For example, on my Linux system:

#include 

        
9条回答
  •  萌比男神i
    2020-12-06 14:30

    Sine of π is 0.0.
    Sine of M_PI is about 1.224647e-16.

    M_PI is not π.

    program gives ... 1.224647e-16 when the correct answer is of course 0.

    Code gave a correct answer to 7 places.


    The following does not print the sine of π. It prints the sine of a number close to π. See below pic.

    π                            // 3.1415926535897932384626433832795...
    printf("%.21\n", M_PI);      // 3.141592653589793115998
    printf("%.21f\n", sin(M_PI));// 0.000000000000000122465
    

    Note: With the math function sine(x), the slope of the curve is -1.0 at x = π. The difference of π and M_PI is about the sin(M_PI) - as expected.


    am running into problems with rounding errors

    The rounding problem occurs when using M_PI to present π. M_PI is the double closest to π, yet since π is irrational and all finite double are rational, they must differ - even by a small amount. So not a direct rounding issue with sin(), cos(), tan(). sin(M_PI) simple exposed the issue started with using an inexact π.


    This problem, with different non-zero results of sin(M_PI), occurs if code used a different FP type like float, long double or double with something other than 53 binary bits of precision. This is not a precision issue so much as a irrational/rational one.

提交回复
热议问题