Search code examples
pythonmathsympysolver

How to solve a (simple) equation with respect to a function using Sympy


First of all sorry for the relatively simple/stupid question, but I really have tried everything and haven't came up with a solution.

I get an equation where symbols (r,theta,M,a) are there, but also a function of r: u_f(r).

uf =sp.Function('u_φ')(r)

If I substitute all the symbols with numerical values, i'll get an expression with u_f(r_0), like this:

MomentumR.subs({theta:sp.pi/2,M:1,a:0.9,r:2})

−0.0115244788566508*uφ^2(2)−0.175486420846152*uφ(2)+0.914728043583324

Although it's a simple equation, how can I solve this with respect to uφ(2) (the above expression is equal to zero in the Solver so thie variable MomentumR is just the above )

I have tried:

FF = `MomentumR.subs({theta:sp.pi/2,M:1,a:0.9,r:2})`
sp.solve(FF,uf)
sp.solve(FF,uf(2))
sp.solve(FF,uf(r))

and many more without results

EDIT: Just to present a simpler but of the same Logic example, If I could solve with respect to G(2), or If I could append a symbol to the function Call G(2), I would essentially solve the 1st problem too. Here is a simple code for it:

import sympy as sp
p = sp.Symbol('p')
M = sp.Symbol('M')
G = sp.Function('G')(p)

Eq = M*3*G**2+M**2*p*G+p
EqS = Eq.subs({M:1,p:2})
EqS 

Solution

  • This is a 'gotcha' related to functions. If you want to be able to give the function a specific argument whenever you want then you need to define the name as a Python function or lambda or as a SymPy Function (not expression) or Lambda.

    This creates something that can't be called; it's like f(r) and you can't do f(r)(r) because f(r) is an expression and you can't call an expression:

    >>> uf =sp.Function('u_φ')(r)
    

    It's simplest to just leave the (r) off in this case. Then,

    >>> uf =sp.Function('u_φ')
    >>> solve(uf(1) - 2)
    [{u_φ(1): 2}]
    >>> solve(uf(x)-2, uf(x))
    [2]
    
    >>>