Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _USE_MATH_DEFINES
- #include <stdio.h>
- #include <math.h>
- const double M = 1.0;
- const double G = 1.0;
- typedef struct {
- double x;
- double y;
- double vx;
- double vy;
- } planet;
- void start(planet *const a, double x0, double y0, double vx0, double vy0){
- a->x = x0;
- a->y = y0;
- a->vx = vx0;
- a->vy = vy0;
- }
- double f(const planet *const a, int i){
- if(i==0)
- return a->vx;
- if(i==1)
- return a->vy;
- if(i==2)
- return -G*M*a->x/pow(a->x*a->x+a->y*a->y, 1.5);
- if(i==3)
- return -G*M*a->y/pow(a->x*a->x+a->y*a->y, 1.5);
- }
- double* get(planet *const a, int i){
- if(i==0)
- return &(a->x);
- if(i==1)
- return &(a->y);
- if(i==2)
- return &(a->vx);
- if(i==3)
- return &(a->vy);
- }
- void set_k(const planet *const a, double *k){
- for(int i = 0; i<4; i++)
- k[i] = f(a, i);
- }
- void next(planet *const old_planet, planet *const new_planet, double dt){
- double k1[4];
- double k2[4];
- double k3[4];
- double k4[4];
- *new_planet=*old_planet;
- set_k(new_planet, k1);
- for(int i = 0; i<4; i++)
- *get(new_planet, i) = *get(old_planet, i)+dt*k1[i]/2;
- set_k(new_planet, k2);
- for(int i = 0; i<4; i++)
- *get(new_planet, i) = *get(old_planet, i)+dt*k2[i]/2;
- set_k(new_planet, k3);
- for(int i = 0; i<4; i++)
- *get(new_planet, i) = *get(old_planet, i)+dt*k3[i];
- set_k(new_planet, k4);
- for(int i = 0; i<4; i++)
- *get(new_planet, i) = *get(old_planet, i)+dt/6*(k1[i]+2*k2[i]+2*k3[i]+k4[i]);
- }
- void print_planet(const planet *const a){
- printf("%.10f %.10f\n", a->x, a->y);
- }
- int main(){
- planet a;
- start(&a, 1, 0, 0, 1);
- double T = 2*M_PI;
- int n = 1000;
- double dt = T/n;
- planet old;
- for(int i = 0; i<n; i++){
- old = a;
- next(&old, &a, dt);
- }
- print_planet(&a);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement