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
|
#include <iostream>
#include <cmath>
using namespace std;
class RungeKutta {
// All your globals are now class members
double gama, OMEGA, zeta, alpha, beta, chi, kappa, phi;
int sistvar;
// These could be here, or back in your rk4 function
double *x_temp1;
double *x_temp2;
double *x_temp3;
double *k1;
double *k2;
double *k3;
double *k4;
public:
RungeKutta(double g, double O, double z,
double a, double b, double c,
double k, double p, int s)
: gama(g),
OMEGA(O),
zeta(z),
alpha(a),
beta(b),
chi(c),
kappa(k),
phi(p),
sistvar(s) {
// create all those arrays based on sistvar size
x_temp1 = new double[sistvar];
x_temp2 = new double[sistvar];
x_temp3 = new double[sistvar];
k1 = new double[sistvar];
k2 = new double[sistvar];
k3 = new double[sistvar];
k4 = new double[sistvar];
}
~RungeKutta() {
// and clean them up
delete [] x_temp1;
delete [] x_temp2;
delete [] x_temp3;
delete [] k1;
delete [] k2;
delete [] k3;
delete [] k4;
}
double F(double t, double x[], int eq);
void rk4(double &t, double x[], double step);
};
double RungeKutta::F(double t, double x[], int eq) {
// gama etc are now your class member variables
if (eq == 0) { return (x[1]); }
else if (eq == 1) { return (gama * sin(OMEGA*t) - zeta * x[1] - alpha * x[0] - beta * pow(x[0], 3) - chi * x[2]); }
else if (eq == 2) { return (-kappa * x[1] - phi * x[2]); }
else { return 0; } //!! NULL is a pointer, not a double
}
void RungeKutta::rk4(double &t, double x[], double step) {
for (int j = 0; j < sistvar; j++)
{
x_temp1[j] = x[j] + 0.5*(k1[j] = step * F(t, x, j));
x_temp2[j] = x[j] + 0.5*(k2[j] = step * F(t + 0.5 * step, x_temp1, j));
x_temp3[j] = x[j] + (k3[j] = step * F(t + 0.5 * step, x_temp2, j));
k4[j] = step * F(t + step, x_temp3, j);
x[j] += (k1[j] + 2 * k2[j] + 2 * k3[j] + k4[j]) / 6.0;
}
t += step;
}
int main()
{
// create an instance, passing in your 9 globals.
RungeKutta myrk(1,2,3,4,5,6,7,8,9);
double t = 0;
double x[10];
myrk.rk4(t,x,1.0); // call the rk4 method
}
| |