C++用泰勒展开式与误差写cos值

我现在遇到的问题是要用泰勒展开式来写出cos的值,并且要输入一个误差值,使得算出来的误差要小于它

img


但途中我遇到的问题是cos之间的转换,想知道为什么在计算cos时,

img


img

可以计算出等价的东西?
(附上完整的程式码

#include<iostream>
#include<cmath>
#include<iomanip>
#include<cstdlib>
#include<math.h> 
using namespace std;

    double Error(double x, int N) {
    double error = 0.0;
    double a = 0.0;
    double b = 0.0;

    // 算誤差的第一部分
    for (int n = 0; n <= N + 1; ++n) {
        double numerator = pow(-1, N + 1);
        double denominator = 2 * (N + 1);
        double power = 2 * (N + 1);
        a += (numerator / tgamma(denominator)) * pow(x, power);
    }

    // 算誤差的第二部分
    for (int n = 0; n <= N; ++n) {
        double numerator = pow(-1, N);
        double denominator = 2 * N;
        double power = 2 * N;
        b += (numerator / tgamma(denominator)) * pow(x, power);
    }

    // 算誤差
    error = abs( a - b );
    return error;
}
    double cos(double x, double e) {
    double result = 0.0;
    double c = 1.0;
    int n = 0;

    while (abs(c) >= e) {
        result += c;
        c *= (-1) * x * x / ((2 * n + 2) * (2 * n + 1));
        ++n;
    }

    return result;
}
int main() {
    double x, e;
    cout << "Enter the value of x: ";
    cin >> x;
    cout << "Enter the allowable error : ";
    cin >> e;

    int N = 0;
    while (Error(x, N) >= e) {
        ++N;
    }
    
 

    cout << " Cos(" << x << ") is equal to " << cos(x,e) << endl;
    

    return 0;
}



为啥答案不就是这个公式了吗?人家明确告诉你cos的泰勒展开式的公式了,
在Error()中你将for循环张开,b不就是等号后面n=N这一大串的内容吗,

img


a就是n=N+1的结果,error=a-b不就是e了吗。

img

cos(x,e)这个函数也一样,只不过里面的C是泰勒展开式的最后一项,但是你仔细看就会发现,上面的error=a-b的结果不也是差在最后一项的值吗,两者同样都是取abs,那不就是同样的结果吗