# From numerical variables to symbolic variables

I would like to define an Hamiltonian dynamics that I will integrate later using scipy.integrate. The Hamiltonian is computed with a symbolic expression and then I need to make substitution from the symbolic variables to the numerical variables.

N=2
var('q1 q2')
var('p1 p2')

zs = [q1,q2,p1,p2]

def dynq(t,z):
H = p1*(q1^2+1/3*q2^2) + p2*(cos(q1)-2*sin(q2*q1)^2)
jacHp = jacobian(H,tuple(ps))
dqdt = list(jacHp)
dqdt.subs({zs[i]:z[i] for i in range(0,2*N)})
dqdt.subs({zs[i]:z[i] for i in range(0,2*N)})
print(dqdt)
return dqdt


I call dynq(0.,[1.,0.5,4.,2.]) and the output is

[q1^2, -2*sin(q1*q2)^2 + cos(q1)]


so q1,q2,p1,p2 are still in the expression and are not replaced by the numerical values of the list $z$.

edit retag close merge delete

Sort by » oldest newest most voted

When you write:

dqdt.subs({qs[i]:z[i] for i in range(0,N)})


this returns another object, it does not change dqdt.

dqdt = dqdt.subs({qs[i]:z[i] for i in range(0,N)})

more