我在找到确切区域和估计错误时遇到问题

计算科学 结石
2021-11-30 05:02:57

程序应首先从键盘读取 a 和 b 的值,然后使用 Simpson 的 1/3 规则估计区间 [a, b] 中 f(x) 下的面积,并显示估计面积和估计误差。其中 f(x)=sqrt(x+1)+0.25,我在数据数组和这个函数中有语法错误:

float f(float data[])
{
    return(sqrt(data[]+1)+0.25);
}

我的其余代码是:

#include<iostream>
#include<cmath>

using namespace std;

//prototype function
float GenerateData(float a ,float b , int n, float data[]);
float f(float data[]);
float Simpson(float a, float b, int n,float data[],float I, float J,float simpson);
float g(float data[]);

//area function
float f(float data[])
{
    return(sqrt(data[]+1)+0.25);
}

// function after ingreation
//float g(float data[])
//{
//    return((2/3)*sqrt(pow(data[]+1),3)+(0.25*data[])+n);
//}

int main()
{
    //decleration
    float a,b,simpson;
    float data[100], I =0, J=0 ;
    int n;

    //input a b and interval
    cout<<"given f(x)=sqrt(x+1)+0.25 "<<endl;

    if (a>b)
    {
        cout<<"error";
    }
    cout<<"please enter lower limit ";
    cin>>a;
    cout<<"please enter upper limit ";
    cin>>b;

    cout<<"please enter the number of intervals ,even number";
    cin>>n;
    if ( n%2!=0)
    {
        cout<<"error";
    }

    //output the estimating area
    cout<< "the estimating area using simpson's rule "<<Simpson( a,  b,  n, data[], I, J,simpson);

    //output the exact area
    //cout<<"the exact area "<<

    //output the error
    //cout<<"The Total Error is : "<<endl;

    return 0;
}




//function generate data
float GenerateData(float a ,float b , int n,float data[])
{
    float xi;
    //using loop
    for(int i=0;i<n+1;i++)
    {
        data[i]=xi=a+i*(b-a/n);
    }

    return data[];
}





// function simpson's rule
float Simpson(float a, float b, int n,float data[],float I, float J,float simpson)
{
    float A;
    //loop
    for(int i=1;i<n;i++)
    {   
        if (i%2!=0)
        {       
            I=I+f(data[i]);
        }
    }

    //loop
    for(int i=2;i<n-1;i++)
    {
        if (i%2==0)
    {       
        J=J+f(data[]);
    }
}

  simpson=(b-a/n*3)*(f(a)+(4*I)+(2*J)+f(b));
  cout<<"The Value of integral under the enterd limits is by using simpson's rule: "<<endl;
  cout<<simpson<<endl;

  return A;
}
1个回答

以下是无效的 C:

return(sqrt(data[]+1)+0.25);

我想你想要的是:

float f(float data[], int n)
{
  float fx = 0.0;
  for(int i=0;i<n;i++){
    fx += sqrt(data[i]+1)+0.25;
  }

  return fx;
}

其中整数输入 n 是数据数组的大小。

编辑

在重新阅读问题时,我认为您想要的是以下功能:

float f(float x)
{
  return sqrt(x+1)+0.25;
}

其中 f 在您的 simpson 函数体(和其他地方)中被调用,例如:

for(int i=1;i<n;i++){
   if(i%2!=0){
     I = I + f(data[i]);
  }
}

注意 1:您对如何实施 simpsons 规则的理解可能存在问题——这会使这个问题成为话题——但是我认为你需要先更好地理解如何编写 C 代码,然后再在此堆栈上发布问题交换。目前使用不正确的 c 代码,很难区分您是否难以理解如何实施 simpsons 规则,或者它是否只是您需要的更多编码经验。祝你好运,我希望这些提示有所帮助。

注意 2:您可以找到确切的面积,因为函数 f(x)=sqrt(x+1)+0.25 的积分可以精确计算(笔和纸)。一旦你有了你的确切面积和你的近似数字面积,就可以将它们进行比较,以找出你的近似值中的错误。具体面积是:

Areaexact=abx+1+0.25dx=(23(x+1)3/2+0.25x)|ab