数值分析实验二 数值积分

    xiaoxiao2021-04-18  65

    (1)、(2)

    #include <iostream>

    #include <cmath>

    using namespace std;

    double f(double x)

    {

    return pow(x,2);

    }

    int main()

    {

    double a,b,e;

    int n;

    cin>>a>>b>>e;

    cin>>n;

    double h=(b-a)/n;

    double x[1000];

    // x[0]=a;另外一种形式

    double result_ti,result_simpson;

    for(int i=0;i<=n;i++)

    {

    x[i]=a+i*h;

    }

    for(int k=0;k<n;k++)

    {

    result_ti+=(h/2)*(f(x[k])+f(x[k+1]));

    result_simpson+=(h/6)*(f(x[k])+4*f((x[k]+x[k+1])/2)+f(x[k+1]));

    }

    /*

    for(int k=1;k<n;k++)

    {

    x[k]=a+h*k;

    mid_ti=(h/2)*(f(a)+2*f(x[k])+f(b));

    // result_simpson=(b-a)/6*(f(a)+4f((a+b)/2)+f(b));

    }

     

    result_ti=(h/2)*(f(a)+mid_ti+f(b));

    */

    cout<<"Ti result: "<<result_ti<<endl;

    cout<<"Simpson result: "<<result_simpson<<endl;

    cout<<"The exact result: "<<(pow(b,3)-pow(a,3))/3<<endl;

    return 0;

    }

    (3)

    //Sin(x)/x in [0,1]

    #include <iostream>

    #include <cmath>

    #define eps 1e-12

    using namespace std;

    double a, b, h;  

    double fx(double x)

    {  

    if (x==0)

    return 1;  

    return sin(x)/x;

    }  

    int main()

    {  

    cin>>a>>b;  

    h = fabs(b-a);  

    double S1, S2, T1, T2, C1, C2, R1, R2;  

    double x, f;  

    T2 = T1 = (fx(a)+fx(b)) * h/2;  

    int k = 0;  

    R1=0; R2=1; h *= 2;  

    while (fabs(R2-R1)>eps)  

    {      

    cout<<T2<<" ";   

    if (k>1)

    cout<<S2<<" ";   

    if (k>2)

    cout<<C2<<" ";   

    if (k>3)

    cout<<R2;   

    cout<<endl;     

    T1 = T2;     

    S1 = S2;

       if (k>1)

    C1 = C2;   

    if (k>2)

       R1 = R2;   

    k++; h/=2;   

    f = 0; x = a + h/2;   

    while (x<b)   

    {    

    f += fx(x);    

    x += h;   

    }   

    T2 = (T1 + h * f) / 2;   

    S2 = T2 + (T2 - T1)/3;   

    if (k==1)

    continue;   

    C2 = S2 + (S2 - S1)/15;   

    if (k==2)

    continue;   

    R2 = C2 + (C2 - C1)/63;    

    }  

    return 0;

    }

    1. 拉格朗日插值在高次插值时同原函数偏差大、存在龙格现象,高次插值多项式不收敛。

    2. 低次插值时,拉格朗日插值精度较高,与原值误差较小

    分段插值时,一般分段越多,精度相应越高

    找规律 #include <iostream> using namespace std;
    转载请注明原文地址: https://ju.6miu.com/read-675312.html

    最新回复(0)