hws02.cpp

来自「hws01:野人和传教士问题 hws02:用Romberg外推法求积分近似值 」· C++ 代码 · 共 106 行

CPP
106
字号
#include<iostream>
#include<cmath>
using namespace std;

double Func1(double x)
{
	return 1/x;
}

double Func2(double x)
{
	return 4/(1+x*x);
}



void GetValueRomberg1(double a,double b,double eps=0.5*pow(10,-8))
{
	int m,n,i,k;
	double y[10],h,ep,p,x,s,q;

	h=b-a;
	y[0]=h*(Func1(a)+Func1(b))/2.0;
	m=1;
	n=1;
	ep=eps+1.0;

	while((ep>=eps)&&(m<=9))
	{
		p=0.0;
		for(i=0;i<=n-1;i++)
		{
			x=a+(i+0.5)*h;
			p=p+Func1(x);
		}
		p=(y[0]+h*p)/2.0;
		s=1.0;
		for(k=1;k<=m;k++)
		{
			cout<<y[k-1]<<" ";
			s=4.0*s;
			q=(s*p-y[k-1])/(s-1.0);
			y[k-1]=p;
			p=q;
			
		}
        cout<<endl;
		ep=fabs(q-y[m-1]);
		m=m+1;
		y[m-1]=q;
		n=n+n;
		h=h/2.0;
	}
	cout<<q<<endl;
	return;
}

void GetValueRomberg2(double a,double b,double eps=0.5*pow(10,-8))
{
	int m,n,i,k;
	double y[10],h,ep,p,x,s,q;

	h=b-a;
	y[0]=h*(Func2(a)+Func2(b))/2.0;
	m=1;
	n=1;
	ep=eps+1.0;

	while((ep>=eps)&&(m<=9))
	{
		p=0.0;
		for(i=0;i<=n-1;i++)
		{
			x=a+(i+0.5)*h;
			p=p+Func2(x);
		}
		p=(y[0]+h*p)/2.0;
		s=1.0;
		for(k=1;k<=m;k++)
		{
			cout<<y[k-1]<<" ";
			s=4.0*s;
			q=(s*p-y[k-1])/(s-1.0);
			y[k-1]=p;
			p=q;
			
		}
        cout<<endl;
		ep=fabs(q-y[m-1]);
		m=m+1;
		y[m-1]=q;
		n=n+n;
		h=h/2.0;
	}
	cout<<q<<endl;
	return;
}

int main()
{
    GetValueRomberg1(1,2,0.5*pow(10,-8));
    cout<<endl;
    GetValueRomberg2(0,1,0.5*pow(10,-8));

	return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?