1

I've seen that Sympy has a sympy.Function feature, but can't find an answer to the following in the documentation.

Is it possible to find custom functions in expressions and use the function definition to simplify them.

As a very simple example, I define the function: f(x) = 2 * exp(x).

Now let's say I have some Sympy expression: 6 * exp(y + z)

Is it possible to tell Sympy to simplify this expression to give a result in terms of the function f.... i.e. so the output from Sympy is: 3 * f(x).

I've found that using .subs() works for simple substitution of variables, but this doesn't seem to work for functions that contain symbols as arguments, as above.

Thanks.

1 Answers1

0

I think what you want to do is not supported by Sympy at the moment (see for instance this stackoverflow question). Nevertheless, something very close can be done with this code:

from sympy import symbols, exp

x, f = symbols('x, f')
expr = 6 * exp(x)
f_func = 2 * exp(x)

print(expr.subs({f_func: f}))
# 3 * f

In the above code I have assumed that the expression you wanted to simplify (expr in the code) was a function of x.

panadestein
  • 1,241
  • 10
  • 21
  • Thanks. Your code suggestion works but this requires the function to be defined in terms of already known arguments... i.e. Sympy couldn't see 2 * exp(y) and change it to f, unless you explicitly define f as being equal to 2 * exp(y) in an ealier line. Let's hope this is an added feature in the future. Thanks anyway. – Qconfused9102 Jun 13 '20 at 18:27
  • What you want (use the variable `y` without explicitly declaring that the function depends on it) is not possible in sympy, and as far as I know, will never be. You need to declare explicitly the symbols to avoid namespace collisions and related issues. It would be my bet that this is a good as you can get, but I might be wrong. Anyway, I hope the answer helped you. Open to discuss if you want. – panadestein Jun 13 '20 at 20:22