Lagrangian for Spring-Pendulum [closed]

I solved a Spring-Pendulum System with NDSolve. I tried to plot a graph with the interpolated data but always returns a message

"An improperly formatted directive with head Symbol was encountered."

Off[Remove::"rmnsm"];
Off[General::"spell1"];
Off[General::"spell"];
Off[Solve::"ifun"];
Remove["*"];
\$Line = 0;
Lagrangiana[T_, V_, Q_: 0, genCoords_List] :=
Module[{L = T - V},
(D[D[L, D[#, t]], t] == Q + D[L, #]) & /@ coord]
SetAttributes[{r0, m, k, g}, Constant]
coord = {r[t], θ[t]}
T = 1/2 m ( r'[t]^2 + r[t]^2 θ'[t]^2)
V = 1/2 k ( r[t] - r0)^2 - m g r[t] Cos[θ[t]]
Q = 0
lagrange = Lagrangiana[T, V, Q, coord]
eq1 = lagrange[[1]] // ExpandAll // FullSimplify
eq2 = lagrange[[2]] // ExpandAll // FullSimplify
Simplify[Solve[lagrange, {r''[t], θ''[t]}]]
{m, k, g, r0} = {1, 1, 9.8, 2};
solucao = NDSolve[{eq1, eq2,
r[0] == r0, Derivative[1][r][0] == 0.,
θ[0] == π/4,
Derivative[1][θ][0] == 0},
{r[t], θ[t]}, {t, 0, 30}];
r[t_] = r[t] /. First[solucao];
Plot[r[t], {t, 0, 15},
AxesLabel -> {"Raio (m)", "Tempo(s)"}]


Any sugestions to solve this problem in the graph?

• Your code works fine here (result). I suggest restarting the kernel or Mathematica to clear out any spurious definitions. – MarcoB May 30 '16 at 20:53
• Is it possible that the version of Mathematica make it? I use v9.01 – dcvilela May 30 '16 at 20:56
• Have you tried restarting, then copying your code from the post and executing just that? Does it still return that error? Also, which line exactly returns your error? – MarcoB May 30 '16 at 20:59
• If I copy and paste it works but in the original code no... – dcvilela May 30 '16 at 21:07
• Hmm that seems to indicate that there is something else in your original notebook that was introducing a spurious definition. It's hard for us to track this down without the rest of your notebook, but I'd suggest that you carefully go through your original code to find the conflicting definition. – MarcoB May 30 '16 at 21:22

1 Answer

If you were to be more careful in your use and scoping of variables, everything would be fine.

{m, k, g, r0} = {1, 1, 9.8, 2};

With[{
Q = 0,
coord = {r[t], θ[t]},
T = 1/2 m (r'[t]^2 + r[t]^2 θ'[t]^2),
V = 1/2 k (r[t] - r0)^2 - m g r[t] Cos[θ[t]]},
Lagrangiana[T_, V_, Q_, coords_List] :=
Module[{L = T - V}, (D[D[L, D[#, t]], t] == Q + D[L, #])& /@ coords];
lagrange = Lagrangiana[T, V, Q, coord]];

With[{
eq1 = lagrange[[1]] // ExpandAll // FullSimplify,
eq2 = lagrange[[2]] // ExpandAll // FullSimplify},
rF =
NDSolve[
{eq1, eq2, r[0] == r0,
Derivative[1][r][0] == 0., θ[0] == π/4, Derivative[1][θ][0] == 0},
{r, θ}, {t, 0, 30}][[1, 1, 2]]];

Plot[rF[t], {t, 0, 15}, AxesLabel -> {"Raio (m)", "Tempo (s)"}]
`