Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sympy: Numerically find root of a symbolic function

Tags:

python

sympy

I have a function whose roots I'd like to find. So far, even Mathematica was inable of finding the roots analytically, so numerically is fine (but please, I'd be happy to be surprised on this matter).

The examples in the documentation all refer to "real" functions, lambda functions, and don't address this issue sufficiently (or I'm just too slow to understand). Here's a simple use case:

from sympy import *
p, r, c, y, lam, f = symbols('p r c y lambda f')
priceCDF = (c*lam*p + c*r - lam*p*r - p*r + r*(c - p)*LambertW(-exp((-c*lam*p - c*r + lam*p*r + lam*r*(c - p) + p*r)/(r*(c - p))), -1))/(lam*r*(c - p))
priceCDFplot = priceCDF.subs(r, 2).subs(c, 0.5).subs(lam, 1)
mpmath.findroot(priceCDFplot, 0.8)

which gives me TypeError: 'Mul' object is not callable. What am I wrong, how do I numerically find the root -- and how could I find it analyitcally?

like image 244
FooBar Avatar asked Oct 26 '25 21:10

FooBar


1 Answers

If you want to use mpmath.findroot, you'll need to convert the SymPy expression to a mpmath expression. The easiest way to do this is with lambdify(p, priceCDF, 'mpmath') (I'm assuming p is the variable you want to solve for).

Another solution would be to use sympy.nsolve, which works directly on SymPy expressions.

like image 193
asmeurer Avatar answered Oct 28 '25 09:10

asmeurer