Search code examples
pythonjupyter-notebooknewtons-method

JUPYTER Newtons Method


Using MATLAB, I am trying to solve the equation using Newtons Method but keep printing the result "None". I am not sure where the mistake is as I do not want to tamper with the formula.

def newt(p):
    maxIt = 1000
    tol = 10^(-5)
    for i in range(maxIt):
        fp = 2*p**3 + p**2 - p + 1 #double * for exponent
        fprimep = 6*p**2 + 2*p - 1 #f'p
        p_new = p - fp/fprimep
        if abs (p - p_new) < tol:
            return p
        p = p_new

#initial values
p0 = -1.2
p = newt(p0)
print(p)

Solution

  • The error in your code is due to a partial conversion from Matlab. You define tol = 10^(-5), but this is not exponentiation in Python, it is bitwise xor. Correcting that, you get the proper result:

    def newt(p):
        maxIt = 1000
        tol = 1e-5   # Error was here
        for i in range(maxIt):
            fp = 2*p**3 + p**2 - p + 1 #double * for exponent
            fprimep = 6*p**2 + 2*p - 1 #f'p
            p_new = p - fp/fprimep
            if abs (p - p_new) < tol:
                return p
            p = p_new
    
    #initial values
    p0 = -1.2
    p = newt(p0)
    print(p)
    # -1.23375
    

    As for the return value, your function returns None when the method does not converge. I'm not sure this was a intentional decision, but it is a good convention anyway, since it allows the user to know the method did not converge. A more robust method would be to throw an exception, maybe adding the guess at the time the iteration stopped and the convergence ratio.