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;
}