Write a program for the secant method using recurssion (tolernace = 0.0001) .Not
ID: 3729860 • Letter: W
Question
Write a program for the secant method using recurssion (tolernace = 0.0001) .Note: it is important that in each recursion call, only 1 function evaluation f(x) is done.
Code below does not use recurssion. Write or add changes to the code below to implement the secant method using recurssion.
tolerance = 0.0001
def non_poly_func(x):
return x**2 + cos(x)**7 + 2*sin(x)
def non_poly_func_der(x):
return 2*x - 7 * cos(x)**6 * sin(x) + 2 * cos(x)
def Secant_recurssion_Q3(f, x0, x1, tolerance):
initial_x0 = x0
initial_x1 = x1
y0 = f(x0)
y1 = f(x1)
num_steps = 0
while (abs(y1) > tolerance):
# y1 / (x1 - x0) / (y1 - y0)
x2 = x1 - y1 * (x1-x0) / (y1-y0)
# updates
x0 = x1
x1 = x2
#y0 = f(x0) # <-- important that this NOT needed (to save running-time)
y0 = y1
y1 = f(x1)
num_steps = num_steps + 1
print ('# [Secant] x0 = ', initial_x0, 'x1 = ', initial_x1, ' after',
num_steps, "steps, approx. root is ", x1)
return x1
Root = Secant_recurssion_Q3 (non_poly_func, 1, 1.02, tolerance)
Explanation / Answer
Find below modified code: If you don't want no. of steps, then remove num_steps argument.
from math import cos, sin
tolerance = 0.0001
def non_poly_func(x):
return x**2 + cos(x)**7 + 2*sin(x)
def non_poly_func_der(x):
return 2*x - 7 * cos(x)**6 * sin(x) + 2 * cos(x)
def Secant_recurssion_Q3(f, x0, x1, tolerance, num_steps):
initial_x0 = x0
initial_x1 = x1
y0 = f(x0)
y1 = f(x1)
if(abs(y1) <= tolerance):
print (num_steps, "steps and approx. root is ", x1)
return x1
else:
# y1 / (x1 - x0) / (y1 - y0)
x2 = x1 - y1 * (x1-x0) / (y1-y0)
# updates
x0 = x1
x1 = x2
#y0 = f(x0) # <-- important that this NOT needed (to save running-time)
y0 = y1
y1 = f(x1)
num_steps = num_steps + 1
return Secant_recurssion_Q3(f, x0, x1, tolerance, num_steps)
Root = Secant_recurssion_Q3 (non_poly_func, 1, 1.02, tolerance, 0)
print(Root)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.