xxxxxxxxxx
# Defining Function
def f(x):
return x**3-5*x-9
# Implementing Bisection Method
def bisection(x0,x1,e):
step = 1
print('\n\n*** BISECTION METHOD IMPLEMENTATION ***')
condition = True
while condition:
x2 = (x0 + x1)/2
print('Iteration-%d, x2 = %0.6f and f(x2) = %0.6f' % (step, x2, f(x2)))
if f(x0) * f(x2) < 0:
x1 = x2
else:
x0 = x2
step = step + 1
condition = abs(f(x2)) > e
print('\nRequired Root is : %0.8f' % x2)
# Input Section
x0 = input('First Guess: ')
x1 = input('Second Guess: ')
e = input('Tolerable Error: ')
# Converting input to float
x0 = float(x0)
x1 = float(x1)
e = float(e)
#Note: You can combine above two section like this
# x0 = float(input('First Guess: '))
# x1 = float(input('Second Guess: '))
# e = float(input('Tolerable Error: '))
# Checking Correctness of initial guess values and bisecting
if f(x0) * f(x1) > 0.0:
print('Given guess values do not bracket the root.')
print('Try Again with different guess values.')
else:
bisection(x0,x1,e)
xxxxxxxxxx
'''By David Oluwafemi(davisphem) || https://linkedin.com/in/davisphem'''
from typing import List, Callable
from math import log2, ceil
def get_n_max(a: float, b: float, tol: float) -> int:
'''get the number of iteration(number of times of bisecting)'''
return ceil(log2(abs(b - a) / tol))
def bisect(f: Callable[[float], float], interval: List[float], tol: float,
n_max: int) -> float:
'''bisect given the number of iteration and tolerance'''
a, b = interval
if f(a) == 0:
return a
elif f(b) == 0:
return b
if a >= b:
raise Exception(
f"arg 'a' should be smaller than arg 'b', but {a} >= {b}")
if not ((f(a) < 0 and f(b) > 0) or (f(a) > 0 and f(b) < 0)):
raise Exception(
f'The function is not continuous on in interval [{a}, {b}]')
n = 0
while n < n_max:
c = (a + b) / 2
if f(c) == 0 or (b - a) / 2 < tol:
return c
n += 1
if f(c) * f(a) < 0:
b = c
elif f(c) * f(a) > 0:
a = c
raise Exception('Method failed')
def bisection_method(f: Callable[[float], float], a: float, b: float,
tol: float) -> float:
'''bisect given the tolerance only'''
n_max = get_n_max(a, b, tol)
return bisect(f, [a, b], tol, n_max)
def main():
'''test using given only tolerance'''
f = lambda x: x**3 - 3 * x + 1
a, b = [0, 1]
tol = 1e-5
print(bisection_method(f, a, b, tol))
if __name__ == '__main__':
main()