Hi! I have this code in C++ that simulates 2 body interacting through gravity using Runge-Kutta 4th order method. I plotted the trajectory of the 2 bodies and as you can see in the first picture they seems to be what I expect, 2 circles. But when I zoom in on one of them (second image) it looks like the circle is not really a circle but more like a spiral. Could you please tell me what might be wrong? Thank you! (The plot is done with python)(adsbygoogle = window.adsbygoogle || []).push({});

<Moderator's note: Please use code tags when posting code>Code (C):

#include<iostream>

#include <vector>

#include<math.h>

#include <fstream>

usingnamespace std;

class Body{

private:

double G= 1;

double rx;

double ry;

double rz;

double vx;

double vy;

double vz;

double mass,ax,ay;

double fx;

double fy;

double fz;

double dt = 0.1;

double initial_x, initial_y,initial_vx,initial_vy;

double dist,dx,dy,dz;

double x1,x2,x3,x4,vx1,vx2,vx3,vx4,ax1,ax2,ax3,ax4;

double y1,y2,y3,y4,vy1,vy2,vy3,vy4,ay1,ay2,ay3,ay4;

public:

Body(double rx, double ry, double rz, double vx, double vy, double vz, double mass){

this->rx=rx;

this->ry=ry;

this->rz=rz;

this->vx=vx;

this->vy=vy;

this->vz=vz;

this->mass=mass;

}

void update(Body b){

dx=b.rx-rx;

dy=b.ry-ry;

dist = sqrt(dx*dx+dy*dy);

ax1=G*b.mass*dx/(dist*dist*dist);

ay1=G*b.mass*dy/(dist*dist*dist);

vx2=vx+ax1*dt*0.5;

vy2=vy+ay1*dt*0.5;

x2=rx+vx*dt*0.5;

y2=ry+vy*dt*0.5;

dx=b.rx-x2;

dy=b.ry-y2;

dist = sqrt(dx*dx+dy*dy);

ax2=G*b.mass*dx/(dist*dist*dist);

ay2=G*b.mass*dy/(dist*dist*dist);

vx3=vx+ax2*dt*0.5;

vy3=vy+ay2*dt*0.5;

x3=rx+vx2*dt*0.5;

y3=ry+vy2*dt*0.5;

dx=b.rx-x3;

dy=b.ry-y3;

dist = sqrt(dx*dx+dy*dy);

ax3=G*b.mass*dx/(dist*dist*dist);

ay3=G*b.mass*dy/(dist*dist*dist);

vx4=vx+ax3*dt;

vy4=vy+ay3*dt;

x4=rx+vx3*dt;

y4=ry+vy3*dt;

dx=b.rx-x4;

dy=b.ry-y4;

dist = sqrt(dx*dx+dy*dy);

ax4=G*b.mass*dx/(dist*dist*dist);

ay4=G*b.mass*dy/(dist*dist*dist);

double nr=1.0/6;

rx=rx+(nr)*(vx+2*vx2+2*vx3+vx4)*dt;

ry=ry+(nr)*(vy+2*vy2+2*vy3+vy4)*dt;

vx=vx+(nr)*(ax1+2*ax2+2*ax3+ax4)*dt;

vy=vy+(nr)*(ay1+2*ay2+2*ay3+ay4)*dt;

}

double get_x(){

return rx;

}

double get_y(){

return ry;

}

double get_vx(){

return vx;

}

};

int main(){

Body body1(0,0,0,0,-0.527046,0,1000), body2(600,0,0,0,1.05409,0,500);

ofstream pos;

pos.open ("Position.txt");

int N=100000;

for(int i; i<N;i++){

body2.update(body1);

body1.update(body2);

pos<<body2.get_x()<<" "<<body2.get_y()<<" "<<body1.get_x()<<" "<<body1.get_y()<<endl;

}

pos.close();

}

**Physics Forums | Science Articles, Homework Help, Discussion**

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# C/++/# Runge-Kutta simulation in C++

Have something to add?

Draft saved
Draft deleted

**Physics Forums | Science Articles, Homework Help, Discussion**