2.94287109375000
sage: def bisection(f, a, b, errorBound):
....: xm = (a+b)/2
....: while f(x) != 0 and (b-a) >= errorBound:
....: if f(a)*f(xm) < 0:
....: b = xm
....: else:
....: a = xm
....: xm = (a+b)/2
....: return xm
sage: bisection(f,3,2,.001).n()
2.50000000000000
which is totally wrong.
sage: f(x) = x^2-9
sage: x = 3
sage: bisection(f,-2,10,1)
4
which is totally wrong.
This is because you use x instead of xm inside bisection.
4) Also, the while loop is not guaranteed to terminate, so a finite loop is better.
5) Finally, as you are looking for a root, it is perhaps best to bound both |f(xm)| and |b–a|.
6) Do not forget that xm is a local variable, so it is not defined outside bisection.
So you could do something similar to the following:
sage: def mybisection(f, aa, bb, maxvalueerror, maxrooterror, maxiter):
....: if abs(f(aa)) < maxrooterror:
....: print("Solution found after 0 iterations.")
....: return aa
....: if abs(f(bb)) < maxrooterror:
....: print("Solution found after 0 iterations.")
....: return bb
....: if aa < bb:
....: a,b = aa,bb
....: else:
....: a,b = bb,aa
....: if f(a)*f(b) > 0:
....: print("No guaranteed solution, stopping.")
....: return None
....: for i in range(maxiter):
....: xm = (a+b)/2
....: if abs(f(xm)) < maxvalueerror and (b-a)/2 < maxrooterror:
....: print("Solution found after "+str(i+1)+" iterations.")
....: return xm
....: if f(a)*f(xm) < 0:
....: b = xm
....: else:
....: a = xm
....: print("No solution found after "+str(maxiter)+" iterations")
....: return None
....:
sage: def f(x):
....: return x^3-9*x+1
....:
sage: x0 = mybisection(f,2,3,10^-12,10^-12,1000)
Solution found after 40 iterations.
sage: x0.n(),f(x0).n()
(2.94282005779587, 5.45047701991629e-13)
sage:
--
You received this message because you are subscribed to the Google Groups "sage-support" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sage-support...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/sage-support/CANnG18-hKhNKG6HFatdOVN1Q9D0A6cxDgpaEqS5Ne5zhsjCyHg%40mail.gmail.com.