Home > Enterprise >  Substituting undefined function in symbolic expression
Substituting undefined function in symbolic expression

Time:10-22

In an expression depending on an unknown function f of r**2, I would like to replace the function f by some actual function and display the result but I cannot find a way to do it. Here's an example:

r = symbols('r', real= True)
phi = r * Function('phi')(r**2)
dphi = phi.diff(r)
print(dphi)

At this stage I get:

2*r**2*Subs(Derivative(phi(_xi_1), _xi_1), _xi_1, r**2)   phi(r**2)

Now let's assume I would like to evaluate dphi when phi(y) = y.

This should give me:

2*r**2   r**2 = 3*r**3

How do I make the actual substitution of phi in dphi to obtain the desired result ?

@Davide_sd This is an example that works as I expect (but for a function of r alone):

r = symbols('r', real= True)
phi = Function('phi')(r)
om = r * phi
dom = om.diff(r)
dom.subs(phi, sin(r)).doit()

output: r * cos(r)  sin(r)

But I would like to have for example (does not work):

r = symbols('r', real= True)
phi = Function('phi')(r**2)
om = r * phi
dom = om.diff(r)
dom.subs(phi, sin(r)).doit()

output: 2*r**2*Subs(Derivative(phi(_xi_1), _xi_1), _xi_1, r**2)   phi(r**2)

Instead I would like to get:

2*r**2*cos(r**2)   sin(2*r**2)

Thanks in advance for any help,

Regards, Bernard.

CodePudding user response:

If you want phi(y) = y this is the Id function; replacement can be done as:

>>> from sympy import Id
>>> dphi.subs(Function('phi'), Id).doit()  # where dphi is as given at the start
3*r**2

In your example for dom it is not clear what function mapping you want since you use phi for the expression Function('phi')(r**2) and for the function Function('phi'). If you mean the same as in the first example -- something like phi(r) = sin(r) then you would just replace Function('phi') with sin.

Another way to approach this is by using replace to find occurrences of the function of interest and replace them with desired value, regardless of argument.

>>> p = Function('phi')
>>> (1 p(x)).replace(lambda x:x.func==p, lambda x:x.args[0]**3)
x**3   1

CodePudding user response:

Based on the above answer and another usage of replace that I discovered here (Why does substitution into a sympy derivative only partly work), here is a summary of two solutions that do exactly what I need:

>>> r = symbols('r', real= True)
>>> phi = Function('phi')
>>> om = r * phi(r**2)
>>> dom = om.diff(r)

# Solution 1
>>> dom.replace(lambda x: x.func == phi, lambda x: x.args[0]**3).doit()
7*r**6

# Solution 2
>>> y = Wild("y")
>>> dom.replace(phi(y), y**3).doit()
7*r**6
  • Related