c++程序来计算e^x
C++ program to calculate e^x
我知道这个问题有很多例子,但我试着自己写一个不同的例子。这是用泰勒级数e^x = 1 + x/1!+ x ^ 2/2 !+ x ^ 3/3 !+……我的代码编译和运行,但它不会输出一些估算的正确答案,我不知道为什么。这是可用的代码吗?还是我应该放弃它?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double final,power,end_n = 1.0,e=1.0,x=2.0, n;
cout<< "n: ";
// usually enter 5 for test
cin>> n;
while (n>1){
power = pow(x,n);
end_n = end_n*n;
e= (power/end_n)+e;
n--;
}
final =e+x;
cout<< final;
return 0;
}
我真的完全不知道你的理由是什么。该特定展开的代码非常简单:
double x;
cin >> x;
double oldres, res=1, top=1, bottom=1;
int iter=1;
do {
oldres=res; // to calculate the difference between iterations
++iter; // next iteration
top*=x; // multiply by one x for each iteration
bottom*=(iter-1); // multiply by the iteration number for each iteration
res+=top/bottom; // and add the fraction to the result
} while(fabs(res-oldres)>.1); // while the difference is still large
cout << res; // done, show the result
要非常清楚一些其他人在暗示:如果你的循环计数从1到n,那么end_n
将等于n!每一步。但是倒数,它没有。请看从1到5的例子:
n | n!
1 | 1
2 | 2
3 | 6
4 | 24
5 | 120
向后n | end_n
5 | 5
4 | 20
3 | 60
2 | 120
1 | 120
由于你的分母绝对没有一个是正确的,如果你的代码只对一些输入是错误的,这是令人惊讶的——事实上,它可能只对x=0是正确的。
最后,我希望这只是一个学习的练习。如果你真的需要e^x的值,你应该使用exp(x)
我想你很接近了。也许你想更像这样:
#include <iostream>
#include <cmath>
using namespace std;
double factorial(long n)
{
double result = n;
while(--n) result*=n;
}
int main()
{
long n, power;
double final, e=1.0, x=2.0;
cout<< "n: ";
// usually enter 5 for test
cin>> n;
while (n>1)
{
power = pow((double)x, (double)n);
end_n = factorial(n);
e = (power/end_n)+e;
n--;
}
final = e+x;
cout<< final;
return 0;
}
你实际上可以采用一个类似horner的方案,以一种基本的方式使用倒计时
1 + x/1!+ x ^ 2/2 !+ x ^ 3/3 !+…+ x^n/n!= (((((x/n + 1) * x/(n - 1) + 1) * x/(n - 2) +…)* x/1 + 1
e = 1.0;
while (n>0){
e = e*x/n + 1;
n--;
}
比较e^x
和1/(e^-x)
对正x
的近似的准确性。
探索(e^(x/4))^4
以获得更好的准确性
相关文章:
- 用C++程序计算圆锥体的体积、球体的体积、八边形的面积和两点之间的距离
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- OpenGL - 在 NDC 中计算位置适用于着色器,但不适用于'regular'程序
- C++用于计算移动平均线的程序
- 我的C++级数计算程序出了什么问题?被困了好几个星期
- 使用 C++ 和 OOP 创建面积计算程序
- 我正在尝试编写一个简单的计算程序,但答案一直返回为 0
- 在c++上创建税务计算程序,错误为未初始化的局部变量
- 不计算程序中的最低和最高成绩。(C++)(流)
- 精确计算C++程序所使用的内存
- 使用OpenMP C++并行计算程序的积分
- 计算C++程序中留下评论的行数
- 计算程序形状的法线
- 如何计算程序的空间复杂度
- C++利息计算程序
- 计算程序集中每个任务的准确 CPU 使用率
- c++计算程序没有响应
- 计算程序中的估计时间
- 如何使大型计算程序更快