【发布时间】:2016-01-12 18:44:31
【问题描述】:
此代码使用辛普森规则计算 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));
}
【问题讨论】:
-
欢迎来到近似和浮点运算的世界。如果你使用一个近似公式,你会得到一个近似的结果。梯形规则最终得到“完全”正确的答案可能是侥幸。
-
是的,这让我感到困惑的是,我认为辛普森的近似值比梯形的误差要小。但我想这可能只是我正在使用的功能的侥幸。谢谢
-
经过 99999 次迭代,我得到了您所需的
1.440422值。有些函数比其他函数收敛得更快,例如有几种方法可以计算pi,但并非所有方法都有用。
标签: c integral simpsons-rule