Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected result of a substitution inside a function argument

In [4]: from sympy import pi, sin, solve, symbols
   ...: t, w0 = symbols('t omega_0')
   ...: wb = 6*w0
   ...: f = sin(wb*t)
   ...: display(f)
   ...: t1 = solve(wb*t-pi, t)
   ...: display(t1)
   ...: f1 = f.subs({t:t1})
   ...: display(f1)
sin(6*omega_0*t)
[pi/(6*omega_0)]
sin(6*omega_0*t)

I expected that the value of the substitution, because there are no more free variables, would be sin(pi) or, even better, 0.
Obviously I’m missing something…


As exposed by Oscar Benjamin in the answer below t1 is a list — as a matter of fact, I need a coffee.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I get an error when I run this code with the latest version of SymPy:

In [4]: f
Out[4]: sin(6⋅ω₀⋅t)

In [5]: t1 = solve(wb*t-pi, t)

In [6]: t1
Out[6]: 
⎡ π  ⎤
⎢────⎥
⎣6⋅ω₀⎦

In [7]: f1 = f.subs({t:t1})
...
SympifyError: [pi/(6*omega_0)]

That’s because t1 is a list. Note that a list is returned because in general an equation to be solved can have more than one solution. You should substitute t for the item in the list which you can refer to as t1[0]:

In [8]: f1 = f.subs({t:t1[0]})

In [9]: f1
Out[9]: 0

Alternatively I recommend using solve with the dict=True argument so that it always returns a list of dicts. Each dict can be used directly with subs:

In [10]: t1 = solve(wb*t-pi, t, dict=True)

In [11]: t1
Out[11]: 
⎡⎧    π  ⎫⎤
⎢⎨t: ────⎬⎥
⎣⎩   6⋅ω₀⎭⎦

In [12]: f.subs(t1[0])
Out[12]: 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading