Pure python single variable function solvers
pip install pyrootspyroots
Abstract
A Python library implementing various root finding methods for single-variable functions.
Currently the following methods have been implemented:
With regard to Brent's method, there are two implementations, the
first one uses inverse quadratic extrapolation (Brentq) while the
other ones uses hyperbolic extrapolation (Brenth).
If you don't know which method to use, you should probably use Brentq.
That being said, Bisect method is safe and slow (i.e. lots of iterations).
Example
# define the function whose root you are searching
def f(x, a):
return x ** 2 - a + 1
# Create the Solver object (instead of Brentq you could also import Brenth/Ridder/Bisect)
from pyroots import Brentq
brent = Brentq(epsilon=1e-5)
# solve the function in `[-3, 0]` while `a` is equal to 2
result = brent(f, -3, 0, a=2)
print(result)
will output:
converged : True
message : Solution converged.
iterations : 6
func calls : 9
x0 : -1.0000000748530762
xtol : 0.0000000000000002
f(x0) : 0.0000001497061579
epsilon : 0.0000100000000000
x_steps : [-3, 0, -0.3333333333333333, -1.6666666666666665, -0.7777777777777779, -1.0686868686868687, -0.9917335278385606, -0.9997244260982788, -1.0000000748530762]
fx_steps : [8, -1, -0.8888888888888888, 1.7777777777777772, -0.3950617283950615, 0.14209162330374459, -0.01646460976088293, -0.0005510718624670563, 1.4970615791476405e-07]
Rationale
The functionality of pyroots is already implemented in scipy, so the
natural question is why rediscover the wheel?
Well, the main reason is that scipy is a huge dependency. Pyroots on
the other hand is just a single package that is easily installed and
that you can easily bundle with py2exe or similar projects. It doesn't
even need to get installed, just throw the pyroots folder in your
project and you are ready to go.
Apart from that, the API used by 's functions is not very user-friendly. For example you can't use keyword arguments for your functions. Moreover, in there is no reliable way to define how many digits of accuracy you want in the obtained root. For example, you may ask for 6 digits, but scipy may calculate up to 14 (or 12 or whatever) digits. The main implication of this "glitch" is that scipy's method may evaluate the function more times than those really needed. If the function calculates something trivial like the functions in the following examples, then these extra function calls are no big deal, but if your functions take significant time to evaluate ,e.g. more than seconds, then this can quickly become annoying, or even, simply unacceptable, e.g. the function takes some minutes to return a value.