Michael A Michael A - 21 days ago 8
Python Question

Why does Sympy substitute values incorrectly?

I have a simple equation like

(f(t) * g(t))^a
, where
a
is a parameter and
f
and
g
are functions of t. The method I'm trying to replicate is


  1. Differentiate the expression with respect to
    t
    , which should be an expression with
    f(t), g(t), f'(t)
    , and `g'(t). In the simple example up above, the result should be

    a * (f(t) * g(t))**(a - 1) * (f'(t) * g(t) + f(t) * g'(t))

  2. Now, we use some knowledge of this specific problem (a problem in economics), where at one specific steady state value only, we know the values of
    f(t)
    and
    g(t)
    . Let's say they're
    f(tss) = 1
    and
    g(tss) = 100
    , where
    tss
    is the steady state value, which I'll set as
    tss = 7
    arbitrarily. These are not the general functional forms of f and g.

  3. Once we substitute in these values, we have an equation with two unknowns: the values of
    f'(tss)
    and
    g'(tss)
    . At this point it doesn't really matter if they're derivatives or not; they're just unknowns, and I have other equations that when combined with this one, give me a non-linear system that I can solve using
    scipy.optimize.fsolve
    or one of sympy's solvers.



The question is, I'm stuck on steps 1 and 2. The code below doesn't seem to substitute the values in correctly.

from sympy import *
t = symbols('t')
a = symbols('a')
f, g = symbols('f g', cls=Function)
eq = (f(t) * g(t))**a
eq_diff = eq.diff(t)
output = eq_diff.evalf(subs={f:1, g:100, a:0.5})
output


This outputs
![derivatives

which doesn't substitute the values at all. What am I doing wrong?

Again, this is just a trivial mathematical example, but it demonstrates the question nicely.

Answer

You could do something like this:

fd, gd = symbols('f_d, g_d')   #values of steady-state derivatives
output.subs({f(t).diff(t):fd, g(t).diff(t):gd, f(t):1, g(t):100, a:Rational(1,2)})

5*f_d + g_d/20