0

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)
  • Looks like you've provided some Python code but you're citing an issue with using MATLAB, it's unclear what your specific issue is. Please [edit] your question to include a [mcve] with the code you're actually having an issue with – Wolfie Mar 03 '22 at 17:40
  • I sure hope you're not trying to run Python code in MATLAB. Also, "I do not want to tamper with the formula" makes it sound like you don't know what the math does, nor what the code does. You've taken someone's code and blindly run it, instead of trying to understand what you are doing. – Cris Luengo Mar 03 '22 at 17:42
  • 1
    If you do want to understand what the code does, look at the for loop: after `maxIt` iterations it exits at the bottom, and the function ends. What value does the function return in this case? – Cris Luengo Mar 03 '22 at 17:43
  • Jupyter Notebook* Doing too many assignments at once. The formula is based on Newton's Method Pn = Pn-1 - (f(Pn-1)/fPrime(Pn-1)). I have done the problem by hand and got -1.23375. Don't assume someone is just taking someone else's code @crisLuengo – Garrett Crawford Mar 03 '22 at 18:15
  • I don't make assumptions, I told you what that sentence conveyed. I was hoping to help you communicate better. Note I said "*makes it sound like*". :) – Cris Luengo Mar 03 '22 at 18:41

1 Answers1

1

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.

nonDucor
  • 2,057
  • 12
  • 17