Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

All published worksheets from http://sagenb.org

Views: 168733
Image: ubuntu2004

Secant Method

Lauri Ruotsalainen, 2010 (based on the application "Root Finding Using Bisection" by William Stein)

Picture:


 

# Secant Method (based on the application "Root Finding Using Bisection" by William Stein) # Lauri Ruotsalainen, 2010 def secant_method(f, a, b, maxn, h): f(x) = f intervals = [(a,b)] round = 1 while True: c = b-(b-a)*f(b)/(f(b)-f(a)) if abs(f(c)) < h or round == maxn: break a, b = b, c intervals.append((a,b)) round += 1 return c, intervals @interact def secant_method_interact( f = x^2-2, a = 0.0, b = 4.0, d = slider(1, 16, 1, 3), maxn = slider(0,15,1,10, label="Max rounds ") ): f(x)=f h = 10^(-d) c, intervals = secant_method(f, float(a), float(b), maxn, h) html("$\\text{Precision h =} 10^{-d}=10^{-%s}=%s$"%(d, float(h))) html("$\\text{c = }%s$"%c) html("$\\text{f(c) = }%s"%f(c)) html("$\\text{Iterations = }%s"%len(intervals)) P = plot(f, a, b, color='red') k = (P.ymax() - P.ymin())/ (1.5*len(intervals)) L = sum(line([(c,k*i), (d,k*i)]) for i, (c,d) in enumerate(intervals) ) L += sum(line([(c,k*i-k/4), (c,k*i+k/4)]) for i, (c,d) in enumerate(intervals) ) L += sum(line([(d,k*i-k/4), (d,k*i+k/4)]) for i, (c,d) in enumerate(intervals) ) S = sum(line([(c,f(c)), (d,f(d)), (d-(d-c)*f(d)/(f(d)-f(c)), 0)], color="green") for (c,d) in intervals) show(P + L + S, xmin=a, xmax=b)