Michael A
Michael A

Reputation: 4613

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.

Upvotes: 2

Views: 514

Answers (3)

asmeurer
asmeurer

Reputation: 91470

Setting just the function name f does not replace it. You need the full expression, such as {f(t): 1} or {f(t).diff(t): 1} (note that the former will replace the derivative with 0).

Upvotes: 0

Stelios
Stelios

Reputation: 5521

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

Upvotes: 1

f5r5e5d
f5r5e5d

Reputation: 3706

sympy 1.0 docs show list of tuples for multiple substitutions:

output = eq_diff.subs([(f, 1), (g, 100), (a, 0.5)])

which for me does the substitution for the symbolic variable a

why expect the f, g function names to be replaced though?

Upvotes: 1

Related Questions