EXP到泰勒系列 [英] EXP to Taylor series
问题描述
我试图将exp(x)函数展开为泰勒级数。这里是代码:
I'am trying to expand exp(x) function to Taylor series. Here is code:
double CalcExp(){
double eps = 0.0000000000000000001;
double elem = 1.0;
double sum = 0.0;
int i = 1;
sum = 0.0;
do {
sum += elem;
elem *= x / i;
i++;
} while (elem >= eps);
return sum;
}
输入大X或负X我的程序崩溃。
当我输入X像0.00000000001时,结果是-1。
The problem is when I enter big X or negative X my program crashes. And when I enter X like "0.00000000001" the result is -1.
需要建议。
推荐答案
对于大X值(大约700及以上),您将达到双精度10 ^ 308),并导致无限循环。你不能做太多,你应该限制X输入范围或使用一些大数字库来扩展范围。
For big X values (around 700 and above), you'll hit the range limit for doubles (10^308) and cause an infinite loop. You can't do much about it, you should either limit X input range or use some big number library to have extended range.
另一个解决方法是将它添加到您的循环中:
Another workaround is to add this to your loop:
if (sum > 1E305) {
// we'll most likely run into an infinite loop
break;
}
注意,你应该在循环后处理这种情况,不正确的结果。
Note you should handle this case outside the loop afterwards to avoid printing a very large incorrect result.
我无法重现 0.00000000001
的问题,负值也运行良好,尽管结果是错误的,这似乎是算法中的错误/限制。编辑:为了纠正这一点,我们可以使用 e ^ -x
与 1 / e ^ x
。
I can't reproduce the problem for 0.00000000001
, this just returns 1 for me. Negative values run fine, too, although the result is wrong which seems to be an error/limitation in the algorithm. To correct this, we can use the fact that e^-x
is the same as 1 / e^x
.
代码:
#include <stdio.h>
double CalcExp(double x){
double eps = 0.0000000000000000001;
double elem = 1.0;
double sum = 0.0;
bool negative = false;
int i = 1;
sum = 0.0;
if (x < 0) {
negative = true;
x = -x;
}
do {
sum += elem;
elem *= x / i;
i++;
if (sum > 1E305) break;
} while (elem >= eps);
if (sum > 1E305) {
// TODO: Handle large input case here
}
if (negative) {
return 1.0 / sum;
} else {
return sum;
}
}
int main() {
printf("%e\n", CalcExp(0.00000000001)); // Output: 1.000000e+000
printf("%e\n", CalcExp(-4)); // Output: 1.831564e-002
printf("%e\n", CalcExp(-45)); // Output: 2.862519e-020
printf("%e\n", CalcExp(1)); // Output: 2.718282e+000
printf("%e\n", CalcExp(750)); // Output: 1.375604e+305
printf("%e\n", CalcExp(7500000)); // Output: 1.058503e+305
printf("%e\n", CalcExp(-450000)); // Output: 9.241336e-308
return 0;
}
这篇关于EXP到泰勒系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!