Skip to content

Instantly share code, notes, and snippets.

@AnuragAnalog
Created July 9, 2021 04:00
Show Gist options
  • Save AnuragAnalog/859c5807bb13ecd85266e77f59019456 to your computer and use it in GitHub Desktop.
Save AnuragAnalog/859c5807bb13ecd85266e77f59019456 to your computer and use it in GitHub Desktop.
Bisection method Implementation in Python
# Bisection method which is also known as bolzano method is based on the repeated application of intermediate value property.
# Let the function f(x) be continous between a and b. For definiteness, let f(a) be (-)ve and f(b) be (+)ve. Then the first approximation to the root is x1 = (a+b)/2.
# If f(x1)=0, then x1 is a root of f(x) = 0, otherwise, the root lies between a
# and x1 or x1 and baccording to f(x1) is (+)ve or (-)ve. Then we bisect the
# interval as before and continue the process until the root is found to the desird accuracy.
#!/usr/bin/python3.6
def f(x):
fx = 3*x**2-15*x+7
return fx
def bisection(a, b):
i = 0
if f(a)*f(b) > 0:
return None
while True:
m = (a+b)/2
print(f"Root after iteration {i} is {m}")
if f(a)*f(m) < 0:
b = m
elif f(b)*f(m) < 0:
a = m
tmp1 = round(a, 9)
tmp2 = round(b, 9)
if tmp1 == tmp2:
return b
i = i + 1
a = float(input("Enter the lower limit of the interval: "))
b = float(input("Enter the upper limit of the interval: "))
root = bisection(a, b)
print(f"The correct root is {root}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment