correct way of using subs()

25 views
Skip to first unread message

Ash

unread,
Jun 13, 2019, 2:43:06 PM6/13/19
to sympy
Hello,

I am having some doubts on how to use subs() in sympy. My aim is to do lagrangian mechanics which involves differentiation.The code below is a cooked up one but I guess it would serve the purpose.

Please look at the code below

from sympy.physics.mechanics import *
import cvxpy

q1, q2 = dynamicsymbols('q1 q2')
q1d, q2d = dynamicsymbols('q1 q2', 1)
L = q1*q1d + q2*q2d
print L.subs(q1, 2).subs(q2, 1).subs(q1d, 3).subs(q2d, 7)

# EXPECTED ANSWER: L = 2*3 + 1*7 = 13
# ACTUAL ANSWER: L = Derivative(1, t) + 2*Derivative(2, t)

Please let me know how  to modify the code to get the expected answer

Thanks
Ash

Aaron Meurer

unread,
Jun 13, 2019, 2:48:03 PM6/13/19
to sympy
Derivatives don't evaluate automatically after subs. You have to call doit().

However, for your example, you are also replacing the derivatives. You
will need to replace the derivatives first. Otherwise you will get 0
because it will have Derivative(1, t) == 0. You can do the
substitution in a single call with

L.subs([(q1d, 3), (q2d, 7), (q1, 2), (q2, 1)])

Or if you are using Python 3.6 or newer:

L.subs({q1d: 3, q2d: 7, q1: 2, q2: 1})

Prior to Python 3.6 dicts are not ordered, so that won't always work
in older versions. But I do recommend using Python 3 for SymPy
regardless as we will be dropping Python 2 support later this year.

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
> To post to this group, send email to sy...@googlegroups.com.
> Visit this group at https://groups.google.com/group/sympy.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/935d0daa-9dc6-4174-990d-d0d7172612ae%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Ash

unread,
Jun 14, 2019, 4:31:57 AM6/14/19
to sympy
Thanks Aaron. Really appreciate. will start to migrate to python3. Thanks again
> To unsubscribe from this group and stop receiving emails from it, send an email to sy...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages