辛普森法则错误

Simpson's Rule error

此代码使用辛普森法则计算 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));
}

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

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

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

怎么强调都不为过 - 始终检查 scanf 的 return 值。

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++)
    {
    

通过这些修复,我使用 n = 1001 获得了 1.440422 的输出。