Lagrangian to Hamiltonian
Here is how you would do it using the standard add-on package VariationalMethods
, which is meant for calculations like this:
Clear[m, k, c, x, t];
T = 1/2 m x'[t]^2;
V = 1/2 k x[t]^2;
L = T - V;
Needs["VariationalMethods`"]
hamiltonianEq =
h == FirstIntegral[t] /. Last[FirstIntegrals[L, {x[t]}, t]]
(* ==> h == 1/2 (k x[t]^2 + m Derivative[1][x][t]^2) *)
momentumEq = p[x] == VariationalD[L, x'[t], t]
(* ==> p[x] == m Derivative[1][x][t] *)
h /.
First[Solve[Eliminate[{hamiltonianEq, momentumEq}, x'[t]], h]]
(* ==> (p[x]^2 + k m x[t]^2)/(2 m) *)
Here, I defined two equations defining the Hamiltonian and momentum using the capabilities of the VariationalMethods
package, and then used Eliminate
to combine these equations into the final result.
The result is in simplified form, but you can also split it into two terms (which is more standard), by adding Apart@
in front of it.
For time-dependent Hamiltonians:
The above works for Hamiltonians that are equal to the conserved energy, as is the case in the question. However, it's easy to modify the definition of hamiltonianEq
above so that it also works in general, following the definition given in the question. You would replace the first equation by
hamiltonianEq = h == x'[t] VariationalD[L, x'[t], t] - L
The rest stays the same.
genCoords = {x[t]};
ke = 1/2 m x'[t]^2;
v = 1/2 k x[t]^2;
q = -c x'[t];
l = ke - v;
Solve for x'[t]
in terms of p[t]
:
rule = First@Solve[p[t] == D[l, x'[t]], x'[t]]
(* {x'[t] -> p[t]/m} *)
and then replace this expression into the Hamiltonian:
x'[t] D[l, x'[t]] - l /. rule
(* p[t]^2/(2 m) + 1/2 k x[t]^2 *)
Note that I have used lower-case symbols for all of your variables. This is to avoid conflicts with built-in Mathematica symbols like K
, which you used. This is good Mathematica practice.