Right now I am trying to make my Runge-Kutta work. Actually I have to solve a ODE-System which is a lot more complicated than this ODE-System, but the runge-kutta-function is the same. I'm solving this simple system to check if the simulation converges to the analytical solution.
First of all I would like to ask you if you see any mistakes in my code. The Problem is, that I get a solution but it differs from the analytical solution (solved it via symbolab). Here is my code:
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
double fx(double x, double y){
return y;
}
double fy(double x, double y){
return x + y;
}
void runge_kutta(double dt, double &x, double &y){
vector<double> k(4), l(4);
#define dt_half dt/2.0
#define dt_six dt/6.0
k.at(0)=fx(x, y);
l.at(0)=fy(x,y);
k.at(1)=fx(x+dt_half*k.at(0), y+dt_half*l.at(0));
l.at(1)=fx(x+dt_half*l.at(0), y+dt_half*l.at(0));
k.at(2)=fx(x+dt_half*k.at(1), y+dt_half*l.at(1));
l.at(2)=fx(x+dt_half*l.at(1), y+dt_half*l.at(1));
k.at(3)=fx(x+dt*k.at(2), y+dt*l.at(2));
l.at(3)=fy(x+dt*k.at(2), y+dt*l.at(2));
x+=dt_six*(k.at(0)+2.0*k.at(1)+2.0*k.at(2)+k.at(3));
y+=dt_six*(l.at(0)+2.0*l.at(1)+2.0*l.at(2)+l.at(3));
}
double t=10.0;
double dt=1e-3;
double x=0.0;
double y=1.0;
ofstream out;
int main(){
out.open("out.txt");
out << "#t, x, y" << endl;
for(double time=0.0;time<t;time+=dt){
cout<<time<<endl;
out << time << ' '
<< x << ' '
<< y << ' '
<< endl;
runge_kutta(dt, x, y);
}
out.close();
}
Can you see any errors?
I'm thankful in advance for any help!