EXP 转 泰勒级数
我正在尝试将 exp(x) 函数扩展到泰勒级数。这是代码:
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 时,我的程序崩溃了。 当我输入“0.00000000001”等 X 时,结果是-1。
需要建议。谢谢你的帮助。
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;
}
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.
Need advice. Thank's for help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于大 X 值(大约 700 及以上),您将达到双精度数的范围限制 (10^308) 并导致无限循环。你对此无能为力,你应该限制 X 输入范围或使用一些大数字库来扩展范围。
另一种解决方法是将其添加到循环中:
请注意,您应该随后在循环之外处理这种情况,以避免打印非常大的错误结果。
我无法重现
0.00000000001
的问题,这只会为我返回 1。负值也运行良好,尽管结果是错误的,这似乎是算法中的错误/限制。编辑:为了纠正这个问题,我们可以使用e^-x
与1 / e^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:
Note you should handle this case outside the loop afterwards to avoid printing a very large incorrect result.
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. EDIT: To correct this, we can use the fact thate^-x
is the same as1 / e^x
.Code:
尝试在调试器中单步调试程序,看看哪里出了问题。如果没有调试器,请在循环中插入打印语句以监视更改的变量值。
Try stepping through your program in a debugger to see where it's going wrong. If you don't have a debugger, insert print statements within the loop to monitor the values of variables that change.