Cài đặt công thức Simpson tính gần đúng tích phân


Mã:
#include "math.h"
#include "conio.h"
#include "iostream.h"

/*Nhap vao mot da thuc luu he so trong A[] va co Bac*/
double*NhapDaThuc(int Bac) {
	double *A = new double [Bac+1];
	for(int i= 0; i<=Bac; i++) {
		cout<<"a"<<i<<" = ";
		cin>>A[i];
	}
	return A;
}

/*Xuat da thuc co he so A[] va Bac*/
void XuatDaThuc( double*A,int Bac, char*s) {
	cout<<"Da Thuc Vua Nhap la:\n";
	cout<<s<<" = "<<A[0];
	for(int i=1; i<=Bac; i++){
		if(A[i]>0) {
			cout<<" + "<<A[i]<<"x^"<<i;
		}
		if(A[i]<0) {
			cout<<A[i]<<"x^"<<i;
		}
	}
}

/*Tinh gia tri cua da thuc tai diem x*/
double f(double*A, int Bac, double x) {
	 double KetQua = A[Bac];
	for(int i=Bac-1; i>=0; i--)
		KetQua=KetQua*x + A[i];
	return KetQua;
}

/*Cong thuc Simpson tich tich phan voi ham f(x)*/
double CongThucSimpson(double*A,int Bac, double a, double b, int n) {
	double h = (b-a)/(2*n);
	double TongFChan=0,TongFLe=0;
	double*F = new double [2*n+1];
	double KetQua;
	for(int i=0; i<=2*n; i++)
		F[i]=f(A,Bac,a+i*h);
	for(i = 1;i<2*n;i++) {
		if(i%2==0)
			TongFChan+=F[i];
		else
			TongFLe+=F[i];
	}
	KetQua = (h/3)*(F[0]+F[2*n]+2*TongFChan+4*TongFLe);
	delete F;
	return KetQua;
}

/*Cong thuc Simpson tinh tich phan voi ham f(x)/g(x)*/
double CongThucSimpson( double*Fx,int BacFx, double*Gx,
						int BacGx, double a, double b, int n) {
	double h = (b-a)/(2*n);
	double TongFChan=0,TongFLe=0;
	double*F = new double [2*n+1];
	double KetQua;
	for(int i=0; i<=2*n; i++) {
		if (f(Gx,BacGx,a+i*h) == 0) {
			cout<<"\nHam f(x)/g(x) khong lien tuc tren [a,b]";
			return -1;
		}
		else {
			F[i]=f(Fx,BacFx,a+i*h)/f(Gx,BacGx,a+i*h);
		}
	}
	for(i = 1;i<2*n;i++) {
		if(i%2==0)
			TongFChan+=F[i];
		else
			TongFLe+=F[i];
	}
	KetQua = (h/3)*(F[0]+F[2*n]+2*TongFChan+4*TongFLe);
	delete F;
	return KetQua;
}

/*Chuong Trinh Chinh*/
void main(){
	clrscr();
	double*Fx,a,b,Epxilon;
	int Bacf,n;
	cout<<"Nhap Vao Bac Cua Da Thuc:";
	cin>>Bacf;
	Fx = NhapDaThuc(Bacf);
	XuatDaThuc(Fx,Bacf,"f(x)");
	cout<<"\nNhap Can Tich Phan a Den b:\n";
	cout<<"a = ";
	cin>>a;
	cout<<"b = ";
	cin>>b;
	cout<<"Nhap Vao So Doan Chia n = ";
	cin>>n;
	cout<<"I = "<<CongThucSimpson(Fx,Bacf,a,b,n);
	getch();
	delete Fx;
}