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)