- #36
cppIStough
- 22
- 2
I can open a new thread if needed, but I thought since this question is right in line with what we spoke about above, perhaps it belongs here. I have the files
rk4.h
and ODE.cpp
I'm trying to make a more general ODE library that can solve ODEs differently, say rk4 vs rk2 for starters. I think the best idea is to have a general class for the ODE method and the inherit from this. However, inheriting the constructor is a challenge. I've googled a ton and no matter what I do I can't get an output now that is not (0,0). If you see what I'm doing please help. I've stepped through code but can't see the issue.
rk4.h
C++:
#pragma once
#include <vector>class ODESolverMethod {
public:
double x0, y0, x_end;
int n;
explicit ODESolverMethod(double x0_, double y0_, double x_end_, int n_) {
double x0 = x0_; double y0 = y0_; double x_end = x_end_; int n = n_;
}
virtual std::vector<std::pair<double, double>>
solve(double f(double x, double y)) = 0;
std::vector<std::pair<double, double>> soln;
};
class RK4 : public ODESolverMethod {
public:
explicit RK4(double x0_, double y0_, double x_end_, int n_) : ODESolverMethod(x0_, y0_, x_end_, n_) {
double x0 = x0_; double y0 = y0_; double x_end = x_end_; int n = n_;
}
std::vector<std::pair<double, double>> solve(double f(double x, double y)) {
double h = (x_end - x0) / n;
soln.push_back(std::make_pair(x0, y0));
auto y_i = y0;
for (int i = 1; i < n + 1; ++i) {
auto x_i = i * h;
auto k1 = f(x_i, y_i);
auto k2 = f(x_i + h / 2, y_i + h * k1 / 2);
auto k3 = f(x_i + h / 2, y_i + h * k2 / 2);
auto k4 = f(x_i + h, y_i + h * k3);
y_i = y_i + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4);
soln.push_back(std::make_pair(x_i, y_i));
}
return soln;
};
std::vector<std::pair<double, double>> soln;
};
and ODE.cpp
C++:
#include "rk4.h"
#include <iostream>double dydx_equals(double x, double y)
{
return x*x*x*exp(-2*x) - 2*y;
}
int main() {
int n = 10;
double x0 = 0.;
double y0 = 1.;
double x_end = 1.;
RK4 solver(x0, y0, x_end, n);
auto soln = solver.solve(dydx_equals);
for (auto iter = soln.begin(); iter != soln.end(); ++iter)
{
std::cout << iter->first << ", " << iter->second << "\n";
}
return 0;
}
I'm trying to make a more general ODE library that can solve ODEs differently, say rk4 vs rk2 for starters. I think the best idea is to have a general class for the ODE method and the inherit from this. However, inheriting the constructor is a challenge. I've googled a ton and no matter what I do I can't get an output now that is not (0,0). If you see what I'm doing please help. I've stepped through code but can't see the issue.