Beijing Institute of Technology | Ming-Jian Li
The following MATLAB code is a companion code for the course on Artificial Intelligence and Simulation Science. It functions to calculate the trajectories of three celestial bodies under the influence of mutual gravity, with time integration performed using the forward Euler method.
491clear; clc;
2
3m1 = 5e4;
4m2 = 4e4;
5m3 = 3e4;
6
7v1 = [2 5 3];
8v2 = [2 -3 -1];
9v3 = [-1.5 1.5 -0.9];
10
11G= 10;
12
13dt = 15;
14tend = 60000;
15t = 0 : dt : tend;
16
17p1 = zeros(length(t), 3);
18p2 = zeros(length(t), 3);
19p3 = zeros(length(t), 3);
20
21p1(1,:)=[-8000 -5000 -6000];
22p2(1,:)=[-3000 7000 5000];
23p3(1,:)=[5000 -7000 5000];
24
25set(gcf,'Position',[200 200 1080 720]);
26
27for i = 2 : length(t)
28 x1 = p1(i-1,:);
29 x2 = p2(i-1,:);
30 x3 = p3(i-1,:);
31 a1 = G*m2 * (x2-x1) / norm(x2-x1).^3 + G*m3*(x3-x1) / norm(x3-x1).^3;
32 a2 = G*m3 * (x3-x2) / norm(x3-x2).^3 + G*m1*(x1-x2) / norm(x1-x2).^3;
33 a3 = G*m1 * (x1-x3) / norm(x1-x3).^3 + G*m2*(x2-x3) / norm(x2-x3).^3;
34 v1 = v1 + a1 * dt;
35 v2 = v2 + a2 * dt;
36 v3 = v3 + a3 * dt;
37 p1(i,:) = p1(i-1,:) + v1 * dt;
38 p2(i,:) = p2(i-1,:) + v2 * dt;
39 p3(i,:) = p3(i-1,:) + v3 * dt;
40 clf
41 plot3(p1(i,1), p1(i,2), p1(i,3), 'r.', "MarkerSize", 40)
42 hold on
43 plot3(p2(i,1), p2(i,2), p2(i,3), 'b.', "MarkerSize", 35)
44 plot3(p3(i,1), p3(i,2), p3(i,3), 'k.', "MarkerSize", 30)
45 plot3(p1(:,1), p1(:,2), p1(:,3), 'r.', "LineWidth", 1.5)
46 plot3(p2(:,1), p2(:,2), p2(:,3), 'b.', "LineWidth", 1.5)
47 plot3(p3(:,1), p3(:,2), p3(:,3), 'k.', "LineWidth", 1.5)
48 pause(0.001);
49end
The results are as follows.