Advertisement
Guest User

hw

a guest
Nov 15th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 KB | None | 0 0
  1. #define _USE_MATH_DEFINES
  2. #include <stdio.h>
  3. #include <math.h>
  4.  
  5. const double M = 1.0;
  6. const double G = 1.0;
  7.  
  8. typedef struct  {
  9.     double x;
  10.     double y;
  11.     double vx;
  12.     double vy;
  13. } planet;
  14.  
  15. void start(planet *const a, double x0, double y0, double vx0, double vy0){
  16.     a->x = x0;
  17.     a->y = y0;
  18.     a->vx = vx0;
  19.     a->vy = vy0;
  20. }
  21.  
  22. double f(const planet *const a, int i){
  23.     if(i==0)
  24.         return a->vx;
  25.     if(i==1)
  26.         return a->vy;
  27.     if(i==2)
  28.         return -G*M*a->x/pow(a->x*a->x+a->y*a->y, 1.5);
  29.     if(i==3)
  30.         return -G*M*a->y/pow(a->x*a->x+a->y*a->y, 1.5);
  31. }
  32.  
  33. double* get(planet *const a, int i){
  34.     if(i==0)
  35.         return &(a->x);
  36.     if(i==1)
  37.         return &(a->y);
  38.     if(i==2)
  39.         return &(a->vx);
  40.     if(i==3)
  41.         return &(a->vy);
  42. }
  43.  
  44. void set_k(const planet *const a, double *k){
  45.     for(int i = 0; i<4; i++)
  46.         k[i] = f(a, i);
  47. }
  48.  
  49. void next(planet *const old_planet, planet *const new_planet, double dt){
  50.     double k1[4];
  51.     double k2[4];
  52.     double k3[4];
  53.     double k4[4];
  54.     *new_planet=*old_planet;
  55.     set_k(new_planet, k1);
  56.  
  57.     for(int i = 0; i<4; i++)
  58.         *get(new_planet, i) = *get(old_planet, i)+dt*k1[i]/2;
  59.     set_k(new_planet, k2);
  60.  
  61.     for(int i = 0; i<4; i++)
  62.         *get(new_planet, i) = *get(old_planet, i)+dt*k2[i]/2;
  63.     set_k(new_planet, k3);
  64.  
  65.     for(int i = 0; i<4; i++)
  66.         *get(new_planet, i) = *get(old_planet, i)+dt*k3[i];
  67.     set_k(new_planet, k4);
  68.  
  69.     for(int i = 0; i<4; i++)
  70.         *get(new_planet, i) = *get(old_planet, i)+dt/6*(k1[i]+2*k2[i]+2*k3[i]+k4[i]);
  71.  
  72. }
  73.  
  74. void print_planet(const planet *const a){
  75.     printf("%.10f %.10f\n", a->x, a->y);
  76. }
  77.  
  78. int main(){
  79.     planet a;
  80.     start(&a, 1, 0, 0, 1);
  81.     double T = 2*M_PI;
  82.     int n = 1000;
  83.     double dt = T/n;
  84.     planet old;
  85.     for(int i = 0; i<n; i++){
  86.         old = a;
  87.         next(&old, &a, dt);
  88.     }
  89.     print_planet(&a);
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement