Calculate the function sin()

前端 未结 4 1271
情书的邮戳
情书的邮戳 2021-01-13 07:04

For my studies, I have to code an algorithm to calculate sin() with this function:

\"\"

4条回答
  •  难免孤独
    2021-01-13 07:23

    Idea about the number of terms with OP's posted answer.

    As long as one performs some range limitation first, like fmod(), the number of terms needed can be reasonably determined dynamically. (Uses 1 to 23 iterations for x: 0 to 2*pi.)

    double sinX1(double x)
    {
        double result = 1.0;
        double term_i = 1.0;
        int i = 2;
    
        x = fmod(x, 2*M_PI);
    
        // for(i = 2; i<= 30; i+=2)
        for(i = 2; ((1.0 + term_i) != 1.0); i+=2)
        {
            term_i = (-term_i * (x*x)) / (i*(i+1));
            result += term_i;
        }
        return x * result;
    }
    

提交回复
热议问题