LagEq[qi_,L_ ,Qi_,t_:t] := 
D[ D[L,(D[qi[t],t])],t]-D[L,qi[t]]==Qi;
  
LagEq[qi_List,L_,Qi_List,t_:t] :=
(D[ D[L,(D[qi[[#]][t],t])],t]-D[L,qi[[#]][t]]==Qi[[#]]
)&  /@  Range[1,Length[qi]];

Protect[LagEq];

Problem 2: Brachistochrone

Clear["Global`*"]

eq1= 2 a ((x'[t])^2)== y[t] (1+ ((x'[t])^2))

sol1=Solve[eq1,x'[t]][[2]]

dsol=DSolve[ y[t] ==a (1-Cos[θ[t]]),y[t],t][[1]]

dydθ= ((D[y[t] /.dsol,t])/(θ'[t]))

dxdy =x'[t]/.sol1 /.dsol

integrand = dydθ dxdy//FullSimplify

int=Integrate[ integrand ,θ[t]]

xAnswer= (int^2) //FullSimplify //Sqrt //PowerExpand

yAnswer=y[t] /.dsol //Simplify

ParametricPlot[ {xAnswer,yAnswer} /.{a->-1},{θ[t],0,10}]

Problem 3: Snell’s law

Clear["Global`*"]

time = ((Sqrt[(a^2)+(x^2)])/v1)+((Sqrt[(b^2)+(((d-x))^2)])/v2);

dt=D[time,x]

rule1= {(x/(Sqrt[(a^2)+(x^2)]))->Sin[θ1],((d-x)/(Sqrt[(b^2)+(((d-x))^2)]))->Sin[θ2]};

eq1=dt==0  /.rule1//Simplify

rule2={v1->(c/n1),v2->(c/n2)};
eq1 //.rule2 //Simplify

Problem 4: hoop on incline

Clear["Global`*"]

Tenergy=(1/2)m ((x'[t])^2) + (1/2)Inertia ((θ'[t])^2) /.{Inertia->m (r^2)}

Vpot=-m g  x[t] Sin[ϕ];

Without Lagrange multiplier

constraint= r θ[t]-x[t]==0;
dsol=DSolve[constraint,θ,t][[1]]

Lag= Tenergy - Vpot /.dsol

eq1= LagEq[ x,Lag,0,t]

Solve[eq1,x''[t]][[1]]

With Lagrange multiplier

constraint= r θ[t]-x[t]==0;
constraint[[1]]

D[constraint[[1]],x[t]]

D[constraint[[1]],θ[t]]

Qlist=λ{D[constraint[[1]],x[t]],D[constraint[[1]],θ[t]]}

Lag= Tenergy - Vpot

eq1= LagEq[ {x,θ},Lag,Qlist,t]

D[constraint,{t,2}]

θsol=Solve[ D[constraint,{t,2}],θ''[t]][[1]]

eq2=eq1 /.θsol

Solve[eq2,{x''[t],λ}][[1]]

Problem 5: Atwood Machine

Clear["Global`*"]

With F-ma

eqs=
{m1 g - Tension == m1 a1,
m2 g - Tension == m2 a2,
a1== - a2}

Solve[eqs,{a1,a2,Tension}][[1]] //Simplify

Without Lagrange multiplier

Tenergy=(1/2)m1 ((x1'[t])^2) +(1/2)m2 ((x2'[t])^2) ;

Vpot=m1 g  x1[t] + m2 g x2[t];

constraint=x1[t]+x2[t]==length;
dsol=DSolve[constraint,x2,t][[1]]

Lag= Tenergy - Vpot /.dsol

eq1= LagEq[ x1,Lag,0,t]

Solve[eq1,x1''[t]][[1]] //Simplify

With Lagrange multiplier

Tenergy=(1/2)m1 ((x1'[t])^2) +(1/2)m2 ((x2'[t])^2) ;

Vpot=m1 g  x1[t] + m2 g x2[t];

constraint=x1[t]+x2[t]-length==0;
dsol=DSolve[constraint,x2,t][[1]]

D[constraint[[1]],x1[t]]

D[constraint[[1]],x2[t]]

Qlist=λ{D[constraint[[1]],x1[t]],D[constraint[[1]],x2[t]]}

Lag= Tenergy - Vpot

eq1= LagEq[ {x1,x2},Lag,Qlist,t]

D[constraint,{t,2}]

sol=Solve[ D[constraint,{t,2}],x2''[t]][[1]]

eq2=eq1 /.sol

Solve[eq2,{x1''[t],λ}][[1]] //Simplify

Problem 7: Bead on Hoop

Clear["Global`*"]

Bead on hoop

Tenergy=(1/2)m( (r^2) ((Sin[θ[t]])^2) (w^2) + (r^2)((θ'[t])^2)) ;

Vpot=- m g r Cos[θ[t]];

Lag= Tenergy - Vpot

eq1= LagEq[ θ,Lag,0,t] //Simplify

eq2= eq1  /.{θ''[t]->0}

sol=Solve[eq2,θ[t]] /.{C[_]:>0}//Simplify //Normal

Cos[θ[t]] /.sol //Simplify

wcrule={r->g/wc^2}

eq2=((eq1[[1]] )/(m (r^2)))  //Expand

eq2=((eq1[[1]] )/(m (r^2)))  /.wcrule//Expand

Series[eq2,{θ[t],0,1}] //Normal