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.
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.