辛普森的规则错误

时间:2015-10-14 15:23:27

标签: c integral simpsons-rule

此代码使用Simpson规则来计算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));
}

1 个答案:

答案 0 :(得分:3)

您看到的问题可能是因为用于读取数字的格式字符串。

scanf("%d %lf,%lf",&n,&y,&z);
         // ^^^ Is the , there on purpose?

尝试从格式字符串中删除,,看看问题是否消失。

不能强调 - 始终检查scanf 的返回值。

if ( scanf("%d %lf %lf", &n, &y, &z) != 3 )
{
   // Deal with error.
}

要确保读取的数字准确无误,请添加一条将输入回送到stdout的行。

printf("n: %d, y: %lf, z: %lf\n", n, y, z);

我发现你的代码中有几处错误:

  1. 时间间隔h不对。由于您使用的是n点,因此有n-1个时间间隔。因此,h必须是:

    h = (z-y)/(n-1); 
    
  2. 由于您要在最后一个语句中添加f(y)f(z),因此循环必须为:

    // Not good to use for(i=0;i<n;i++)
    for(i=1;i<n-1;i++)
    {
    
  3. 通过这些修补程序,我使用1.440422获得n = 1001的输出。