gpt4 book ai didi

c - C 语言泰勒级数逻辑

转载 作者:行者123 更新时间:2023-11-30 18:30:21 24 4
gpt4 key购买 nike

我正在开发一个项目,我们使用泰勒级数来近似 e^x,其中 x 是用户输入的值。我们给出的测试值是 x=.5、x=1.0 和 x=1.5。目标是让输出应该是一个表格,其中包含创建系列的循环的每次迭代的一行,第一列包含迭代次数,第二列包含理论值(基于 exp(x) ),第三为求和的总和,第四为理论值与迭代值的差值。

我当前的代码如下。就目前而言,我的逻辑有一些漏洞,因为代码构建并运行,但输出不正确。如果我要解决我的问题,我认为我的求和没有从正确的位置开始(1),并且前两项是错误的(1+x+(x^2/2!)+(x ^3/3!)...等等)。

与我所拥有的逻辑相比,我应该使用什么逻辑?谢谢。

//cs 1325
// Dean Davis
// Dr. Paulk
// series convergence homework.

#include <stdio.h>
#include <float.h> // need it for FLT_EPSILON
#include <math.h>


unsigned long factorial(int); // function will calculate the factorial

int main()
{
int n = 0;
unsigned long fact; // this variable will hold the factorial value
float x; // this will be the value read in from the user
double theoval; // this will hold the theoretical value of e^x
double holder; // will hold the value of the nth term
double total = 0; // will accumulate the total summation
double diff; // will hold the sifferential between theoretical value and the summation
puts("Please enter a numerical value greater than zero: "); // request input
scanf_s("%f", &x); // read it in
theoval=exp(x); // calc the theoretical value

printf("# Iter e^x Sum Diff\n");
printf("------- ------- ------- -------\n"); // set up the output

while ((theoval - total) >= FLT_EPSILON) //the loop to continue to sum the summation
{
fact = factorial(n); // calls the factorial function
holder = (pow(x, n)) / fact; // calculates the term n
total = total + holder; // adds to the sum
diff = theoval - total; // calc the diff
printf(" %-9d%-12.6f%-14.6f%-10.8f\n", n, theoval, total, diff); // output it
if ((theoval - total) >= FLT_EPSILON) // if it is smaller, then we don't wan't to increment n
continue;
else
n++;
}

printf("The number of iterations required for convergence is: %d\n", n); // out put this line

}


unsigned long factorial(int n)
{
unsigned long int fact=n;
if (n == 0) // if n is zero, 0!=1
return 1;
else // so long as it is not, then we can calculate it like this
{
n--; // decrement it
for (n; n > 0; n--)
{
fact = fact*n; // multiply the next number by the product of all the preceding terms
}
return fact;
}
}

最佳答案

您的主要问题在这里:

    if ((theoval - total) >= FLT_EPSILON) // if it is smaller, then we don't wan't to increment n
continue;
else
n++;

这个逻辑既落后又不必要。它是向后的,因为您避免在您想要增加 n 的情况下增加它,并且这是不必要的,因为在其他情况下您无论如何都会退出循环,因为 while表达式为假。只需无条件地增加 n 即可。

这个表达也有点可疑:

(theoval - total) >= FLT_EPSILON

FLT_EPSILON接近1.0的可表示浮点值之间的间距有关。不同地方的间距是不同的,所以用它作为绝对误差界限是没有意义的。由于泰勒级数以余项的形式有一个明确定义的误差界限,我建议改为计算当前 n 的余项的最大可能值,如果该界限的比率则退出当前总和的错误值小于某个相当小的值,例如可能0.00001

关于c - C 语言泰勒级数逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31576165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com