SciPy Newton Method

3.3k views Asked by At

I need to find the roots of a quite complicated equation and I've read that python has a set of function that can help. I tried to figure out how they work but I failed pretty bad. The examples that I saw are all quite simple instead I need to find the roots of this function:

enter image description here

With B and K real positive numbers. Can anyone help ?

1

There are 1 answers

2
J. P. Petersen On BEST ANSWER

Here are two solutions, the second is probably the simpler and more correct way of solving the problem.

The trick is that you have to get the function f to remember the values of K and B. One way of doing this is to make it an inner function of another function. The outer function is used to set K and B. These are in the variable scope of the inner function that is returned. This way the inner f function can remember the values. The returned function is then simply passed on to the Newton-Raphson method, and it finds the root.

from scipy.misc import factorial
from scipy.optimize import newton
import numpy as np

def get_f(K=1, B=1):
    def f(x):
        return np.exp(-B*(np.power(B, x))-factorial(x)*K)
    return f

f = get_f(K=2, B=3)
print newton(f, 3, maxiter=1000)

A user commented that the newton function has an args argument, which can be used to pass extra arguments to the Newton-Raphson function. If the function has the form f(x, a, b, c...), then a, b, c... are extra arguments that can be given in args.

The same solution would then look like this:

from scipy.misc import factorial
from scipy.optimize import newton
import numpy as np

def f(x, K, B):
    return np.exp(-B*(np.power(B, x))-factorial(x)*K)

print newton(f, 3, args=(2, 3), maxiter=1000)