2
$\begingroup$

I have been trying to make a simple animation of planetary motion, but I can't seem to get it to work. I'm still new to this program so I am not sure how to make it work. Can anyone help?

Here is my code,

Clear["Global`*"]
G = 1;
m1 = 1;
m2 = 1;
T = 10;

r[t_] := Sqrt[x[t]^2 + y[t]^2];

eqns = {x''[t] == -((G m2)/(r[t]^3) ) x[t], x'[0] == 0, x[0] == 1, 
  y''[t] == -((G m2)/(r[t]^3) ) y[t], y'[0] == 0.5, y[0] == 0}

{x, y} = NDSolveValue[eqns, {x, y}, {t, 0, T}]
Animate[ParametricPlot[{x[t], y[t]}, {t, 0, T}, 
  PlotRange -> {{-3, 3}, {-3, 3}}, PlotStyle -> {Red, Thick}], {t, 0, 
  1}]
$\endgroup$
2
  • 1
    $\begingroup$ looks good to me except for the Animate[..., {t, 0, 1}], in part because t is local to ParametricPlot there. I'm not quite sure what output you want, because ParametricPlot ranges over all t already...do you maybe want to vary T instead? or Show a point moving on top of the ParametricPlot? $\endgroup$
    – thorimur
    May 12 at 20:23
  • $\begingroup$ @thorimur I think that the point is to generate an animated graph in time; if I understand correctly. So instead of showing the full plot at once, generating it in some sense as it evolves in t $\endgroup$ May 12 at 20:39
2
$\begingroup$

If I understand correctly what you wanted to code, I believe that the following might be a good/helpful starting point. If you don't find this useful and/or relevant, please let me know and I will delete it.

G = 1;
m1 = 1;
m2 = 1;
T = 10;

r[t_] := Sqrt[x[t]^2 + y[t]^2];

eqns = {x''[t] == -((G m2)/(r[t]^3)) x[t], x'[0] == 0, x[0] == 1, 
   y''[t] == -((G m2)/(r[t]^3)) y[t], y'[0] == 0.5, y[0] == 0};

This is the part that has some minor tweaks compared to the original code

sltn = NDSolve[eqns, {x[t], y[t]}, {t, 0, T}] // Flatten;

And then

p1 = ListAnimate[
  Table[Plot[{Evaluate[x[t] /. sltn[[1]]]}, {t, 0, tmax}, 
    PlotRange -> {{0, T}, {-2, 2}}], {tmax, 10^-5, T, 0.1}]]
p2 = ListAnimate[
  Table[Plot[{Evaluate[y[t] /. sltn[[2]]]}, {t, 0, tmax}, 
    PlotRange -> {{0, T}, {-2, 2}}], {tmax, 10^-5, T, 0.1}]]
$\endgroup$
2
$\begingroup$
Clear["Global`*"]
G = 1;
m1 = 1;
m2 = 1;
T = 10;

r[t_] := Sqrt[x[t]^2 + y[t]^2];

eqns = {x''[t] == -((G m2)/(r[t]^3) ) x[t], x'[0] == 0, x[0] == 1, 
  y''[t] == -((G m2)/(r[t]^3) ) y[t], y'[0] == 0.5, y[0] == 0}

All that's needed is to fix a couple variable names.

{xsol, ysol} = NDSolveValue[eqns, {x, y}, {t, 0, T}]

Animate[ParametricPlot[{xsol[t], ysol[t]}, {t, 0, tt}, 
  PlotRange -> {{-3, 3}, {-3, 3}}, PlotStyle -> {Red, Thick}], {tt, 0.1, 3}]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.