1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
|
/* myRungeKutta.h */
/* ================== */
#ifndef MyRungeKutta_h
#define MyRungeKutta_h
#include "RungeKutta.h"
class MyRungeKutta:public RungeKutta
{
public:
MyRungeKutta(int ln):RungeKutta(ln){};
void set(double la){a=la;}
virtual void fk(const double *x, double *f)const;
virtual void fkh(const double *x, double *f)const;
private:
double a;
};
#endif
/* RungeKutta.h */
/* ================== */
#ifndef RungeKutta_h
#define RungeKutta_h
class RungeKutta
{
public:
RungeKutta(int ln);
~RungeKutta();
void step();
virtual void fk(const double x, double *f)const { };
virtual void fkh(const double x, double *fh)const { };
double& operator[](int i){return x[i];}
protected:
int n; //number of equations
double *x; //pointer to function
};
#endif
/* main.cpp */
/* ================== */
#include <iostream>
#include <iomanip>
#include <math.h>
#include "myRungeKutta.h"
using namespace std;
int main()
{
int a=1;
int n=2;
double t=0.0, h=0.1;
cout << "*** Runges ir Kutos Metodas: Masyvai ***" << endl;
cout << " dx[0]/dt = -x[1], dx[1]/dt=0 " << endl;
cout << " t = 0: x[0]=1, x[1] = 0" << endl;
cout << setw(3) << " t " << setw(3) << "x[0] " << setw(3) << " cos(t) " << setw(3) << " x[1] " << setw(3) << "sin(t) " << endl;
cout << "--------------------------------------" << endl;
for (int i = 0; i<=10; i++){
MyRungeKutta X(n);
X[0]=1;
X[1]=0;
cout << setw(3) << fixed << setprecision(1) << t << " ";
cout << setw(3) << fixed << setprecision(4) << X[0] << " ";
cout << setw(3) << fixed << setprecision(4) << cos(t) << " ";
cout << setw(3) << fixed << setprecision(4) << X[1] << " ";
cout << setw(3) << fixed << setprecision(4) << sin(t) << endl;
t=t+h;
}
return 0;
}
/* myRungeKutta.cpp */
/* ================== */
#include "myRungeKutta.h"
void MyRungeKutta::fk(const double *x, double *f) const
{
f[0] = -x[1]*a;
f[1] = x[0]*a;
}
void MyRungeKutta::fkh(const double *x, double *f) const
{
f[2] = -x[3]*a;
f[3] = x[2]*a;
}
/* RungeKutta.cpp */
/* ================== */
#include "RungeKutta.h"
RungeKutta::RungeKutta(int ln)
{
n=ln;
x = new double[n];
}
RungeKutta::~RungeKutta()
{
delete []x;
}
void RungeKutta::step(){
double f[]={0.0,0.0,0.0,0.0};
fk(*x,f);
x[2]=x[0]+0.1*f[0];
x[3]=x[1]+0.1*f[1];
fkh(*x,f);
x[0]=x[0]+0.1/2*(f[0]+ f[2]);
x[1]=x[1]+0.1/2*(f[1]+ f[3]);
}
|