Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Using Newton-Raphson Iterative Process To Solve A Quadratic Equation
- def newton(f,Df,x0,epsilon,max_iter):
- xn = x0
- lastfxn = -9999
- for n in range(0, max_iter):
- # fxn = f(xn) # <<== I could not get these function calls to be accepted. See next line.
- fxn = xn ** 2 - xn - 6
- # Uncomment the next line to get a trace of the progress of the algorithm
- print("Iteration #", n + 1, " xn=", xn, " fxn=", fxn, " last=", lastfxn)
- # if abs(fxn) < epsilon: # <<== this is wrong, see next line
- if abs(fxn - lastfxn) < epsilon:
- print('Found solution after', n + 1, 'iterations.')
- return xn
- lastfxn = fxn # Remember the latest result obtained, so we can compare with next iteration
- # Dfxn = Df(xn) # <<== I could not get these function calls to be accepted. See next line.
- Dfxn = 2 * xn - 1
- if Dfxn == 0:
- print('Zero derivative. No solution found.')
- return None
- else:
- xn = xn - fxn / Dfxn
- print('Exceeded maximum iterations. No solution found.')
- return None
- # f(xn) = lambda x: x**2 - x - 6
- # Df(xn) = lambda x: 2*x - 1
- # print (newton(f(xn),Df(xn),1,1e-10,10)) # I could not get those function parameters to work
- print(newton("dummy", "dummy", 1, 1e-10, 10))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement