In: Computer Science
Make a python function that inputs f : a function whose root you wish to find, x0 : an initial guess for the root, x1 : an second guess for the root, and k : a number of iterations, and output and outputs a list of the results of performing the secant method k times starting from x0 and x1. Use your function to check if the secant method has the claimed rate of convergence when applied to f ( x ) = e x + x starting with x 0 = 3 and x 1 = 2
import math
def secant(f,x0,x1,k):
if f(x0)*f(x1) >= 0:
print("Secant method fails.")
return None
x0_n = x0
x1_n = x1
results = []
for n in range(1, k+1):
m_n = x0_n - f(x0_n)*(x1_n - x0_n)/(f(x1_n) - f(x0_n))
f_m_n = f(m_n)
if f(x0_n)*f_m_n < 0:
x0_n = x0_n
x1_n = m_n
elif f(x1_n)*f_m_n < 0:
x0_n = m_n
x1_n = x1_n
elif f_m_n == 0:
print("Found exact solution.")
return m_n
else:
print("Secant method fails.")
return None
results.append(m_n)
return results
def f(x):
return math.exp(x) * x
print(secant(f, -3, 2, 100))
We get:
Screenshot of the code: