Please complete the Python 3 code to solve for f(x) = 0 using the Secant method
ID: 3878427 • Letter: P
Question
Please complete the Python 3 code to solve for f(x) = 0 using the Secant method for rootfinding.
Secant method The secant method is similar to Newton's method, but instead of evaluating f'(x) directly, it uses the approximation i-Xi- def secant(f, a, b, tol-1e-10): "Solve f(x) using the secant method" history = [] xlast, flast = b, f(b)[0] # We'LL use x-b as our Last evaluation to initialize x=(a + b) / 2 for i in range(100): # And start with the midpoint as the current guess fx = f(x)[0] history.append((x, if numpy.abs(fx) fx)) tol: break # YOUR CODE HERE #raise NotImplementedError() return numpy.array(history)Explanation / Answer
# cook your dish here
def secant(f,a,b, TOL=0.001, NMAX=100):
history=[]
xlast,flast=b,f(b)[0]
"""
Takes a function f, start values [x0,x1], tolerance value(optional) TOL and
max number of iterations(optional) NMAX and returns the root of the equation
using the secant method.
"""
for i in range(NMAX):
fx=f(x)[0]
history.append(x,fx)
if numpy.abs(fx)<TOL:
break
x = b - f(b)*((b-a)/(f(b)-f(a)))
if x-b < TOL:
return x
else:
a = b
b = x
return numpy.array(history)
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.