gboffi
gboffi

Reputation: 25023

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.

Upvotes: 0

Views: 28

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14480

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

Upvotes: 2

Related Questions