使用Maclaurin级数近似计算cos(x)

Dea*_*one 3 c

所以,我正在尝试创建一个程序,通过使用泰勒近似来计算cos(x).

程序非常简单:用户输入参数x(x是以弧度表示的角度)和浮点ε,它是cos(x)值的精度.

基本上,程序唯一要做的就是计算这个总和:x ^ 0/0! - x ^ 2/2!+ x ^ 4/4! - x ^ 6!+ x ^ 8/8! - ...,直到项小于ε,即cos(x)的值,它将在我们的精度范围内.

那么,这是代码:

#include <stdio.h>

/* Calculates cos(x) by using a Taylor approximation:
   cos(x) = x^0/(0!) - x^2/(2!) + x^4/(4!) - x^6/(6!) + x^8/(8!) - ... */

int main(void)
{    
    int   k;         // dummy variable k

    float x,         // parameter of cos(x), in radians
          epsilon;   // precision of cos(x) (cos = sum ± epsilon)
          sum,       // sum of the terms of the polynomial series
          term;      // variable that stores each term of the summation

    scanf("%f %f", &x, &epsilon);

    sum = term = 1, k = 0;

    while (term >= epsilon && -term <= epsilon) 
    // while abs(term) is smaller than epsilon
    {
        k += 2;
        term *= -(x*x)/(k*(k-1));
        sum += term;
    }

    printf("cos(%f) = %f\n", x, sum);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

起初,我试图通过计算单独变量"fact"上的阶乘来解决它,尽管即使合理的ε大值也会导致溢出.

为了解决这个问题,我注意到我可以将前一个项乘以-x²/(k(k - 1)),在每次迭代中将k增加2,以得到下一个项.我认为这可以解决我的问题,但话说再说,它不起作用.

程序编译很好,但是,例如,如果我输入:

3.141593 0.001

输出是:

cos(3.141593)= -3.934803

......这显然是错误的.有人能帮我吗?

cha*_*e55 5

错误在于你的while循环:

while (term >= epsilon && -term <= epsilon)
Run Code Online (Sandbox Code Playgroud)

这不是正确的条件.虽然可以通过修复逻辑来修复:

while (term >= epsilon || -term >= epsilon)
Run Code Online (Sandbox Code Playgroud)

您应该只使用标准的浮点abs函数fabs,因为它使代码的功能更加明显:

while (fabs(term) >= epsilon)
Run Code Online (Sandbox Code Playgroud)

应用该更改并编译程序后,我用它来计算cos(3.141593) = -1.000004,这是正确的.

  • `cos(x)<-1`这怎么可能是正确的:-) (2认同)