Advertisement
acclivity

pyNewtonRaphsonQuadratic

Jan 28th, 2021
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. # Using Newton-Raphson Iterative Process To Solve A Quadratic Equation
  2.  
  3. def newton(f,Df,x0,epsilon,max_iter):
  4.     xn = x0
  5.     lastfxn = -9999
  6.     for n in range(0, max_iter):
  7.  
  8.         # fxn = f(xn)               # <<== I could not get these function calls to be accepted. See next line.
  9.         fxn = xn ** 2 - xn - 6
  10.  
  11.         # Uncomment the next line to get a trace of the progress of the algorithm
  12.         print("Iteration #", n + 1, "  xn=", xn, "  fxn=", fxn, "  last=", lastfxn)
  13.  
  14.         # if abs(fxn) < epsilon:                 # <<== this is wrong, see next line
  15.         if abs(fxn - lastfxn) < epsilon:
  16.             print('Found solution after', n + 1, 'iterations.')
  17.             return xn
  18.         lastfxn = fxn               # Remember the latest result obtained, so we can compare with next iteration
  19.  
  20.         # Dfxn = Df(xn)             # <<== I could not get these function calls to be accepted. See next line.
  21.         Dfxn = 2 * xn - 1
  22.  
  23.         if Dfxn == 0:
  24.             print('Zero derivative. No solution found.')
  25.             return None
  26.         else:
  27.             xn = xn - fxn / Dfxn
  28.  
  29.     print('Exceeded maximum iterations. No solution found.')
  30.     return None
  31.  
  32.  
  33. # f(xn) = lambda x: x**2 - x - 6
  34. # Df(xn) = lambda x: 2*x - 1
  35. # print (newton(f(xn),Df(xn),1,1e-10,10))       # I could not get those function parameters to work
  36. print(newton("dummy", "dummy", 1, 1e-10, 10))
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement