该代码使用辛普森法则来计算X * SIN(X)与(1,2)边界的积分。我遇到的问题是,它的实际价值非常接近。即使有999次迭代,它仍然没有达到要求。虽然我有一个单独的程序,它使用梯形法则来处理同样的事情,并且它在1000次迭代后恰好达到了这一点。它应该打的一点是“1.440422”辛普森规则错误
是什么应该发生的事情对辛普森的规则?或者我的代码有问题吗?
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
double f(double x);
int main()
{
double x,result,y,z,h,s1,s2;
s1 = 0;
s2 = 0;
int i,n;
printf("\nHow many points to you want it evaluated at (odd number)? And what are the bounds? lower bound,upper bound >\n");
scanf("%d %lf,%lf",&n,&y,&z);
h = (z-y)/n;
result = 0;
if(n%2!=0)
{
for(i=0;i<n;i++)
{
if(i%2==0)
{
s1 = s1+f(y+i*h);
}
else
{
s2 = s2+f(y+i*h);
}
}
result = (h/3)*(f(y)+f(z)+4*s2+2*s1);
printf("\nThe value is %lf with %d interations\n",result,i);
}
else
{
printf("\n The number of points has to be odd, try again\n");
}
}
double f(double x)
{
return(x*sin(x));
}
欢迎近似的世界和浮点运算。如果您使用近似公式,则会得到近似结果。这可能是一种侥幸,这个梯形法则最终会以'正确'的正确答案结束。 –
是的,那令我困惑的部分是我认为辛普森的近似值比梯形误差更小。但我想这可能只是我正在使用的功能而已。谢谢 – user3908631
在99999次迭代中,我得到了你需要的值'1.440422'。一些函数比其他函数更快地收敛,例如有几种方法可以计算'pi',但并非全部都有用。 –