如何计算序列e^(-x)的和,精度e=0.0001

How to calculate a sum of sequence e^(-x) with accuracy E=0.0001?

本文关键字:的和 精度 0001 何计算 计算      更新时间:2023-10-16

所以我可以计算序列的和而不精确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)?对不起英语。

这是e^(-x)的泰勒级数吗?如果是这样,你就写错了。我认为你所拥有的不会趋同。

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

备注:我建议对浮动垃圾使用doublef后缀(例如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);

指数函数