The approximator can be written in C++ code below

Header file1: Deflnt_header.h

#pragma once

class Deflnt {
	private:
		double a;
		double b;
		double (*f) (double x);

	public:
		Deflnt();
		Deflnt(const Deflnt& d);
		Deflnt(double aa, double bb, double (*function)(double x));
		double ByTrapzoid(int N);
		double BySimpson();

};

Cpp file1 :Defint.cpp

#include "Deflnt_header.h"
#include <iostream>
#include <cmath>
using namespace std;


Deflnt::Deflnt(double aa, double bb, double(*function)(double x)) {
	a = aa;
	b = bb;
	f = function;
}

Deflnt::Deflnt(const Deflnt& d)
{
	a = d.a;
	b = d.b;
	f = d.f;
}


double Deflnt::ByTrapzoid(int N) {
	double h = (b - a) / N;
	double sum = f(a);
	for (int k = 1; k < N; k++) {
		sum += 2 * f(a + h * k);
	}
	sum += f(b);
	return ((b - a) * sum) / (2 * N);

}



double Deflnt::BySimpson() {
	return (b - a) * (f(a) + 4 * f((a + b) / 2) + f(b)) / 6;
}



Cpp file2: main.cpp


#include <iostream>

#include "Deflnt_header.h"
#include <iostream>
#include <cmath>
using namespace std;
double f(double x) {
	return x * x * x - x * x + 1;
}
int main()
{
	Deflnt MyInt(1.0, 2.0, *f);
	int N;
	cout << "enterstep N "; cin >> N;
	cout << "Trapzoid val " << endl;
	cout << MyInt.ByTrapzoid(N) << endl;

	cout << "Simpson val " << endl;
	cout << MyInt.BySimpson() << endl;
	return 0;
}

Leave a comment

Trending