如何计算序列e^(-x)的和,精度e=0.0001
How to calculate a sum of sequence e^(-x) with accuracy E=0.0001?
所以我可以计算序列的和而不精确E.
int t=1, x, k;
float sum, a, result, factorial=1, E=0.0001;
for(k=0;k<=(n);k++){
while(t<=n){
factorial*=t;
t++;
}
sum=(pow(-x,k))/factorial;
sum+=sum;
//while(fabs(sum-???)<E){
// result=sum;
//}
}
所以我知道序列的和sum(k)。但要精确计算E,我必须知道以前元素的和sum(k-1)。如何从中获得循环的sum(k-1)?对不起英语。
http://www.efunda.com/math/taylor_series/exponential.cfm
e^(-x)是1+(-x(-x)^3/3!+。。。
double calculate_power_of_e(double xx, double accuracy) {
double sum(1.0);
double term(1.0);
for (long kk=1; true; ++kk) {
term *= (-xx) / kk;
sum += term;
if (fabs(term) < accuracy)
break;
}
return sum;
}
printf("e^(-x)" = %.4fn", calculate_power_of_e(5.0, .0001));
首先要说明您应用的幂公式:根据维基百科,您应该添加术语pow(-x,k)/(k!)
,而不是pow(-x,k)/(n!)
。
这导致了代码的小优化:作为k! = k * (k-1)!
,我们可以避免内部while
循环和许多无用的乘法运算。
顺便说一句,你构建总和的方式也有一个错误:你总是抹掉以前的结果,然后再加上第二次当前项。
一旦纠正了这一点,你只需要注意一个额外的变量:
double myexpo(double x, int n=100) {
int k;
double sum = 1.0, pvsum, factorial = 1.0, E = 0.0001;
for (k = 1; k <= (n); k++){ // start with 1
pvsum = sum;
factorial *= k; // don't calculate factorial for 0.
sum += (pow(-x, k)) / factorial;
if (k > 1 && fabs(sum - pvsum) < E) { // check if diff is small enough
cout << k << " iterations" << endl;
break; // interupt the for loop if it's precise enough
}
}
return sum; // at the end of the loop sum is the best approximation
}
你可以用这个测试这个功能:
double x;
do {
cout << "Enter number: ";
cin >> x;
cout << myexpo(x) << endl;
cout << exp(-x) << endl;
} while (x > 0);
备注:我建议对浮动垃圾使用double
或f
后缀(例如0.001f),即使它按原样工作。
检查术语的绝对值何时小于您想要的精度。
double sum = 0, x = 1, k = 0, E = 0.0001, fact = 1;
while(true){
double term = pow(-x, k) / fact;
if(fabs(term) < E)
break;
sum += term;
fact *= (++k);
}
printf("e^(-x) = %.4f", sum);
当该术语与1.0相比微不足道时,停止循环。
通过使用递归,并且|x|
不太大,首先求和最小项。
e(x) = 1 + x/1! + x*x/2! + x*x*x/3! + ...
double my_exp_term(double x, double term, unsigned n) {
if (term + 1.0 == 1.0) return term;
n++;
return term + my_exp_term(x, term*x/n, n);
}
double my_exp(double x) {
return 1.0 + my_exp_term(x, x, 1);
}
double y = my_exp(-1);
指数函数
相关文章:
- 为什么虚函数不能是静态的和全局的?
- 获取向量C++中第一个值和最后一个值的和
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 在程序变得低效之前,允许多少新的[]和删除[]分配是否有限制?
- 在 Windows/C++ 上使用多进程应用程序的高精度定时操作
- 为什么 Clang std::ostream 写一个 std::istream 无法读取的双精度?
- 将标准输入中的双精度存储在矢量中
- Fmod 函数清楚地输出一个预期的双精度值,但 if(fmod == 预期的双精度值)的计算结果不是 true
- 将大的双精度数写入 TXT 文件C++
- 从.txt文件读取到C++中的双精度向量
- 分析字符串中的双精度和单词
- C和C++标准的数学精度要求
- 如何计算序列e^(-x)的和,精度e=0.0001
- vb.net和c++之间的文字精度为0.57
- 将范围有限的浮点数转换为无符号的整数,以保持排序顺序和精度
- 计算双精度数组中所有元素的和
- 为零填充宽度和精度与要打印的整型参数相同
- 使用EXPECT_EQ计算双精度或浮点数的和时出错