泰勒展开的计算方法

e^x的泰勒展开

#include<iostream>
using namespace std;

int main() {
    int n;
    double x;
    cout << "Enter the value of n: ";
    cin >> n;
    cout >> "Enter the value of x:";
    cin >> x;

    double sum = 1.0;
    double term = 1.0;

    for (int i = 1; i <= n; ++i) {
        term *= x / i;
        sum += term;
    }

    cout << "e^x for n=" << n << " is approximately: " << sum << endl;

    return 0;
}

sin(x)的泰勒展开

1.利用循环运算

#include<iostream>

#include<cmath>

using namespace std;

int main() {

double term, x, n, sum;

int i;

cout << "Please enter x:";

cin >> x;

sum = x;

term = x;

cout << "Please enter n:";

cin >> n;

for (i = 2; i <= n; i++)

{

term = -term * x * x / (2 * i - 1) / (2 * i - 2);

if (fabs(term) <= 1e-6) break;

sum += term;

}

cout << "sum=" << sum << endl;

return 0;

}

2.使用幂函数pow和阶乘函数tgamma

#include <iostream>
#include <cmath>

using namespace std;

int main() {
    double x, sum = 0.0, term;
    int n;

    cout << "Enter the value of x: ";
    cin >> x;

    cout << "Enter the number of terms (n): ";
    cin >> n;

    for (int i = 0; i < n; ++i) {
        term = pow(-1, i) * pow(x, 2 * i + 1) / tgamma(2 * i + 2);
        //掌握pow和tgamma函数 tgamma(n)代表的是(n-1)! tgamma(n + 1)才是n的阶乘
        sum += term;

        if (fabs(term) < 1e-6) {
            break;
        }
    }

    cout << "sin(" << x << ") for " << n << " terms is approximately: " << sum << endl;

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值