Numerical Method Problem! Write the program in Python! The number pi is a soluti
ID: 3788470 • Letter: N
Question
Numerical Method Problem! Write the program in Python!
The number pi is a solution of sin x = 0. Apply the Newton-Raphson iteration to f(x) = sin(x) with x_0 = 3 as start point. As a stopping criterion use the condition max {|x_n-2 Write a little Python, or C, or other C-like function for this Newton-Raphson iteration. Use double precision. One program can answer all the questions (2.1, 2.2, 2.3, 2.4) (but make it clear where your answers are). What is n at the stopping point? What is max {|x_n-2 - x_n-1|, |x_n-1 - x_n|} for this n? What is the value of x_n at the stopping point?Explanation / Answer
import math
def derivative(x):
return math.cos(x) # might want to return a small non-zero if ==0
def quadratic(x):
return math.sin(x) # just a function to show it works
def solve(f, x0):
lastlastX = x0 #initially X0
lastX =lastlastX - (f(lastlastX)/derivative(lastlastX) ) # initially X1
nextX = lastX - (f(lastX)/derivative(lastX) ) #initially X2
n = 2 # as we already calculate two values so n valu is 2
while(max(abs(lastlastX-lastX),abs(lastX-nextX) ) > 0.5*math.pow(10,-9)): # this is how you terminate the loop
newY = f(lastX) # just for debug... see what happens
print ("f(", lastX, ") = ",newY) # print out progress... again just debug
lastlastX = lastX
lastX = nextX
nextX = lastX - (f(lastX)/derivative(lastX) ) # update estimate using N-R
n = n+1
print ("value of n at stopping point :",n) # 2.2 value of n at stopping point
print ("max diff ", max(abs(lastlastX-lastX),abs(lastX-nextX)) ) # 2.3
return nextX
xFound = solve(quadratic, 3) # call the solver
print ("value at stopping point: Xn = ", xFound ) # 2.4 value of x at stopping point
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.