【发布时间】:2013-10-08 06:10:03
【问题描述】:
我一直在编写泰勒级数的程序,并使用 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));
}
【问题讨论】:
-
当包含两个术语时,问题甚至仍然存在 1 - 1/x -exp(-x) 并且它仍然给出大于 1 + 1/x -exp(x) 的值 - 问题是当 x = 1 时非常明显。
-
我在您的代码中没有看到可以使用负指数的任何地方。我看到 pow(x[i], k),这基本上意味着 x[i]^k,并且 k 在您的代码中始终是正数。 exp(-x) 是什么意思?
标签: exponential