Write a Python procedure to implement basic Newton\'s Method. The definition sta
ID: 3802352 • Letter: W
Question
Write a Python procedure to implement basic Newton's Method. The definition statement of your program should be def Newt(f, fp, x0, TOL, N): where f and fp are the function and derivative, x0 is the initial guess, TOL is the stopping tolerance, and N is the maximum number of iterations allowed. Implement the stopping condition where the difference of the iterates is less than the tolerance. Test your program on the function f(x) = x - cos x on [0, 1]. Print out each iteration and compare with the numbers from class or Excel. Use 20 as the maximum number of iterations. Your output statement should be of the form: The solution to the equation is XXXX in NNNN iterations. or The solution wasn't found in N iterations. Where X0X0X0 is the initial value x_0, XXXX is the value the sequence converges to and NNNN is the number of iterations it takes to converge.Explanation / Answer
CODE:
# Newton Raphson Method.
import math
"""
* Variable Description:
*
* f : Given function
* fp : Derivative of f
* x0 : Initial value
* TOL : Tolerance
* N : Max number of iterations
"""
def Newt(f, fp, x0, TOL, N):
"""
Takes a function f, its derivative fp, initial value x0, tolerance value TOL and
max number of iterations N and returns the root of the equation
using the newton-raphson method.
"""
n=1
while n<=N:
# use the Newton Raphson formula to calculate the root
x1 = x0 - (f(x0)/fp(x0))
print x1
# Compare with the Tolerance value.
if x1 - x0 < TOL:
return (x1,n)
else:
x0 = x1
# Increment the iteration count.
n += 1
return (False,n)
if __name__ == "__main__":
# f(x) = x - cos(x)
def func(x):
return x-math.cos(x)
# fp(x) = 1 + sin(x)
def func_(x):
return 1+math.sin(x)
#Invoking Newton Raphson Method
res,iter = Newt(func,func_,0.1,0.0001,20)
if res != False:
print "The solution to the equation is " + str(res) + " in " + str(iter) + " iterations."
else:
print "The solution wasn't found in " + str(iter) + " iterations."
OUTPUT:
$python newton.py
0.913763386101
0.744664241982
The solution to the equation is 0.744664241982 in 2 iterations.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.