我一直在为泰勒级数编写程序,并使用long double作为数字格式来允许计算大数。对于正指数,我的程序工作得很好,但是对于负指数,它会失败。问题是,当我为某些x计算exp(-x)时,我得到的正数非常大。这可能是什么原因?感谢您的帮助。您可以在这里看到我的代码:
#include <stdio.h>
#include <math.h>
//We need to write a factorial function beforehand, since we
//have factorial in the denominators.
//Remembering that factorials are defined for integers; it is
//possible to define factorials of non-integer numbers using
//Gamma Function but we will omit that.
//We first declare the factorial function as follows:
long double factorial (double);
//Long long integer format only allows numbers in the order of 10^18 so
//we shall use the sign bit in order to increase our range.
//Now we define it,
long double
factorial(double n)
{
//Here s is the free parameter which is increased by one in each step and
//pro is the initial product and by setting pro to be 0 we also cover the
//case of zero factorial.
int s = 1;
long double pro = 1;
if (n < 0)
printf("Factorial is not defined for a negative number \n");
else {
while (n >= s) {
pro *= s;
s++;
}
return pro;
}
}
int main ()
{
long double x[13] = { 1, 5, 10, 15, 20, 50, 100, -1, -5, -10, -20, -50, -100};
//Here an array named "calc" is defined to store
//the values of x.
//int k;
////The upper index controls the accuracy of the Taylor Series, so
////it is suitable to make it an adjustable parameter.
int p = 135;
long double series[13][p];
long double sum = 0;
int i, k;
for (i = 0; i <= 12;i++) {
for (k = 0; k <= p; k++){
series[i][k] = pow(x[i], k)/( factorial(k));
sum += series[i][k];
}
printf("Approximation for x = %Lf is %Lf \n", x[i], sum);
}
printf("%Lf \n", factorial(100));
}
Run Code Online (Sandbox Code Playgroud)
这只是您进行数值分析的数学主题。MacLaurin系列适用e^x于所有人x,但让我们看看为什么它对没有用e^(-10)。
e^x = 1 + x + x^2/2 + x^3/6 + x^4/24 + x^5/120 + x^6/720 + x^7/5040 + ... +x^n/n! + ...
e^(-10) = 1 - 10 + 100/2 - 1000/6 + 10000/24 -100000/120 + ...
Run Code Online (Sandbox Code Playgroud)
该系列中最大的术语是什么?10^10/10!大约是2755.7319224。什么是真正的价值e^(-10) 约0.00004539992。一路累加起来,序列会损失9位精度,而这是您所没有的。
如果您找到e^(10)并接受了对等,那您将相当安全。如果您通过乘以(1 / e)10倍来直接计算e ^(-10),那也是安全的。但是,任何包含交替项的序列在数量级上可能比真实答案大得多时,都会引起这些问题。
即使对于范围有限的功能,实际上也不会使用MacLaurin系列。例如,首先使用trig函数的参数,并使用周期性和trig恒等式将参数减少为interval 0 < ? < ?/4。然后,通常采用Chebychev逼近来平均减少误差。在其他情况下,连续分数和Pade近似值比三角级数更好。贝塞尔函数最好通过向后递归来完成。
看一本好的数值分析书。Forman Acton的“ 通常可以使用的数值方法”是老式的,但是很好。