class, simple ode 2

Simple ordinary differential equation with euler explicit, predictor corrector euler and second order Runge Kutta.

Main.cpp


//============================================================================
// Name        : ode.cpp
// Author      : chd
// Version     :
// Copyright   : Your copyright notice
// Description : Simple ordinary differential
//               equation class.Euler explicit method, euler predictor corrector
//				 and second order Runge-Kutta, C++ Ansi-style
//============================================================================

#include <iostream>
#include "ode.h"
#include "srcFunction.h"
using namespace std;

int main() {
	ode odef(0,2,3,f);
	double* sol=odef.euler(100);
	double* sol2=odef.eulerPredCorr(100);
	double* sol3=odef.rungeKutta2(100);
	for (int i = 0; i < 100; ++i) {
		cout<<"|"<<sol[i]<<"|";

	}
	cout<<endl;
	for (int i = 0; i < 100; ++i) {
			cout<<"|"<<sol2[i]<<"|";
	}
	cout<<endl;
	for (int i = 0; i < 100; ++i) {
				cout<<"|"<<sol3[i]<<"|";
	}
}

ode.h


/*
 * ode.h
 *
 *  Created on: Mar 14, 2016
 *      Author: christos
 */

#ifndef ODE_H_
#define ODE_H_

class ode{

private:

	double tstart;
	double tend;
	double x0;
	double (*sfn)(double t, double x);

public:
	ode(double t0,double tn,double xinit, double (*f)(double t,double x)){

		tstart=t0;
		tend=tn;
		x0=xinit;
		sfn=f;

	}


	double* euler(int n) const;
	double* eulerPredCorr(int n) const;
	double* rungeKutta2(int n) const;

};




#endif /* ODE_H_ */

ode.cpp

/*
 * ode.cpp
 *
 *  Created on: Mar 14, 2016
 *      Author: christos
 */
#include "ode.h"

double* ode::euler(int n) const{

	double* x=new double[n+1];
	double h=(tend-tstart)/n;
	x[0]=x0;
	for (int i = 0; i < n; ++i) {
		x[i+1]=x[i]+ h*sfn(tstart+h*i,x[i]);
	}
	return x;
}


double* ode::eulerPredCorr(int n) const{

	double* x=new double[n+1];
	double h=(tend-tstart)/n;
	x[0]=x0;
	for (int i = 0; i < n; ++i) {

		//predictor
		x[i+1]=x[i]+h*sfn(tstart+h*i,x[i]);
		x[i+1]=x[i]+h*sfn(tstart+h*(i+1),x[i+1]);
	}
	return x;
}

double* ode::rungeKutta2(int n) const{

	double* x=new double[n+1];
	double h=(tend-tstart)/n;
	x[0]=x0;
	for (int i = 0; i < n; ++i) {
		double f1=h*sfn(tstart+h*i,x[i]);
		double f2=h*sfn(tstart+h*(i+1),x[i]+f1);
		x[i+1]=x[i]+(f1+f2)/2;
	}

	return x;

}




srcFunction.cpp


/*
 * srcFunction.cpp
 *
 *  Created on: Mar 14, 2016
 *      Author: christos
 */

#include "srcFunction.h"


double f(double t, double x){


	return x*(1-exp(t))/(1+exp(t));


}