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
|
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cmath>
#include <utility>
using namespace std;
double dx2(int t, int x, int dx)
{
return (-9.8*cos(x));
}
std::pair<double, double> RK4(float t, float x, float dx, float h)
{
double k1, k2, k3, k4, l1, l2, l3, l4, diff1, diff2;
k1 = h*dx2(t,x,dx);
l1 = h*k1;
k2 = h*dx2(t+h/2,x+l1/2,dx+k1/2);
l2 = h*k2;
k3 = h*dx2(t+h/2,x+l2/2,dx+k2/2);
l3 = h*k3;
k4 = h*dx2(t+h,x+l3,dx+k3);
l4 = h*k4;
diff1 = (l1+2*l2+2*l3+l4)/float(6);
diff2 = (k1+2*k2+2*k3+k4)/float(6);
return {diff1, diff2};
}
int main()
{
double t0, t1, x0, dx0, h, N;
N = 1000;
t0 = 0;
int myints[] = {t0};
std::vector<int> t(myints, myints + sizeof(myints) / sizeof(int) );
t1 = 10;
x0 = 0;
int myints1[] = {x0};
std::vector<int> x(myints1, myints1 + sizeof(myints1) / sizeof(int) );
dx0 = 0;
int myints2[] = {dx0};
std::vector<int> dx(myints2, myints2 + sizeof(myints2) / sizeof(int) );
h = (t1 - t0) / float(N);
for(int i = 1; i<=N; i++) {
auto diff = RK4(t[i-1],x[i-1],dx[i-1],h);
x.push_back( x[i-1] + diff.first );
dx.push_back(dx[i-1] + diff.second );
t.push_back( t[i-1] + h);
}
cout << x[N];
return 0;
}
|