problem2_3body.m 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. clear all; close all; clc;
  2. % Constants
  3. G = 6.674e-11; % N m^2 kg^-2
  4. M_sun = 1.989e30; % kg
  5. M_earth = 5.972e24; % kg
  6. M_mars = 6.39e23; % kg
  7. r_earth_sun = 1.496e11; % m
  8. r_mars_sun = 2.279e11; % m
  9. year = 365.25 * 24 * 60 * 60; % s
  10. % Task 1, calculate orbital velocities
  11. v_earth = sqrt((G*M_sun)/r_earth_sun);
  12. v_mars = sqrt((G*M_sun)/r_mars_sun);
  13. % Task 2, set up initial conditions
  14. initial_conditions = [0 0 r_earth_sun 0 r_mars_sun 0 0 0 0 v_earth 0 0.85*v_mars];
  15. % Task 3, solve the position over time from gravitational force
  16. % We're doing this twice with beta=2 and beta=2.01
  17. t_span = [0 10*year];
  18. force1 = @(t, Y) threeBodyODE(t, Y, G, M_sun, M_earth, M_mars, 2);
  19. force2 = @(t, Y) threeBodyODE(t, Y, G, M_sun, M_earth, M_mars, 2.01);
  20. options = odeset('RelTol', 1e-6, 'AbsTol', 1e-6);
  21. [t1, Y1] = ode45(force1, t_span, initial_conditions, options);
  22. [t2, Y2] = ode45(force2, t_span, initial_conditions, options);
  23. x1 = Y1(:, 1);
  24. y1 = Y1(:, 2);
  25. x2 = Y1(:, 3);
  26. y2 = Y1(:, 4);
  27. x3 = Y1(:, 5);
  28. y3 = Y1(:, 6);
  29. figure;
  30. hold on;
  31. xlim([min([x1;x2;x3]), max([x1;x2;x3])]);
  32. ylim([min([y1;y2;y3]), max([y1;y2;y3])]);
  33. plot(x1, y1, 'yo', 'MarkerFaceColor', 'y', 'MarkerSize', 25);
  34. plot(x2, y2, 'g-');
  35. plot(x3, y3, 'r-');
  36. legend('Sun', 'Earth Path', 'Mars Path');
  37. xlabel('x (m)');
  38. ylabel('y (m)');
  39. title("Sun, Earth, and Mars path over 10 years (beta = 2)")
  40. x1 = Y2(:, 1);
  41. y1 = Y2(:, 2);
  42. x2 = Y2(:, 3);
  43. y2 = Y2(:, 4);
  44. x3 = Y2(:, 5);
  45. y3 = Y2(:, 6);
  46. figure;
  47. hold on;
  48. xlim([min([x1;x2;x3]), max([x1;x2;x3])]);
  49. ylim([min([y1;y2;y3]), max([y1;y2;y3])]);
  50. plot(x1, y1, 'yo', 'MarkerFaceColor', 'y', 'MarkerSize', 25);
  51. plot(x2, y2, 'g-');
  52. plot(x3, y3, 'r-');
  53. legend('Sun', 'Earth Path', 'Mars Path');
  54. legend('Sun', 'Earth Path', 'Mars Path');
  55. xlabel('x (m)');
  56. ylabel('y (m)');
  57. title("Sun, Earth, and Mars path over 10 years (beta = 2.01)")