Hi, my question involves solving a system of two ODEs using the 2nd order Runge-Kutta method. I have managed to use the 2nd order Runge-Kutta to solve a single differential equation, however in this instance I have ODEs; dx/dt = v, dv/dt = -x and I'm unsure how to edit my working code to account these two equations. The code below is the working code, I would appreciate it if someone could give me a direction to go in to solve a similar problem with the coupled ODEs. From looking on the internet it seems that I have to use vectors to solve it, is this the right idea? Any information would be super helpful. Thanks.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <math.h>
#include <fstream>
constdouble pi = 4*atan(1);
double f(double y)
{
double a = 1 + y*y;
return a;
}
int main()
{
double h, y, m, N, k1, k2;
int i = 0;
printf("\nPlease enter an integer \n");
std::cin >> N;
y = 0;
h = (pi/4)/N;
while (i < N)
{
k1 = h*f(y);
k2 = h*f(y + k1/2);
y = y + k2;
i++;
printf("%f\n",y);
}
}
If you have code to solve dy/dt=f (as posted) you should be able to change it readily to solve
d/dt(x,v)=(v,-x)
Your y is replaced by pair (x,v) and your function f must return (v,-x).
Or, looked at another way, ...
Your y is replaced by (y0,y1) and your function f must return (f0,f1)=(y1,-y0).
So, yes, you can usefully code with y and f as vectors. Your coupled ODEs will give you the components of those vectors. If you wanted your main steps (lines 27-29) to look more like the vector operations that you would write down on paper, then consider using valarray<> rather than normal vector<>. Then you wouldn't have to explicitly write loops to cycle through the vector components.