File indexing completed on 2026-04-09 07:48:46
0001
0002 """
0003 https://personal.math.ubc.ca/~pwalls/math-python/roots-optimization/bisection/
0004
0005
0006 """
0007
0008 def bisect(f,a,b,N):
0009 '''Approximate solution of f(x)=0 on interval [a,b] by bisection method.
0010
0011 Parameters
0012 ----------
0013 f : function
0014 The function for which we are trying to approximate a solution f(x)=0.
0015 a,b : numbers
0016 The interval in which to search for a solution. The function returns
0017 None if f(a)*f(b) >= 0 since a solution is not guaranteed.
0018 N : (positive) integer
0019 The number of iterations to implement.
0020
0021 Returns
0022 -------
0023 x_N : number
0024 The midpoint of the Nth interval computed by the bisection method. The
0025 initial interval [a_0,b_0] is given by [a,b]. If f(m_n) == 0 for some
0026 midpoint m_n = (a_n + b_n)/2, then the function returns this solution.
0027 If all signs of values f(a_n), f(b_n) and f(m_n) are the same at any
0028 iteration, the bisection method fails and return None.
0029
0030 Examples
0031 --------
0032 >>> f = lambda x: x**2 - x - 1
0033 >>> bisection(f,1,2,25)
0034 1.618033990263939
0035 >>> f = lambda x: (2*x - 1)*(x - 3)
0036 >>> bisection(f,0,1,10)
0037 0.5
0038 '''
0039 if f(a)*f(b) >= 0:
0040 print("Bisection method fails.")
0041 return None
0042 a_n = a
0043 b_n = b
0044 for n in range(1,N+1):
0045 m_n = (a_n + b_n)/2
0046 f_m_n = f(m_n)
0047 if f(a_n)*f_m_n < 0:
0048 a_n = a_n
0049 b_n = m_n
0050 elif f(b_n)*f_m_n < 0:
0051 a_n = m_n
0052 b_n = b_n
0053 elif f_m_n == 0:
0054 print("Found exact solution.")
0055 return m_n
0056 else:
0057 print("Bisection method fails.")
0058 return None
0059 return (a_n + b_n)/2