PYTHON code bisection method:
In [ ]:
def bisection_method(func,a,b,error_accept):
def f(x):
return eval(func)
error=abs(b-a)
while error > error_accept:
c=(a+b)/2
if f(a)*f(b)>=0:
print("the bisection method will not work!")
quit()
elif f(c)*f(a)<0:
b=c
error=abs(b-a)
elif f(c)*f(b)<0:
a=c
error=abs(b-a)
else:
print("something went wrong")
return
print(f"here the error is {error} which is less then provided epsilon =
print(f"the approximated root {(a + b) / 2.0}")
bisection_method("(4*x**3)+3*x-3", 0, 1, 0.05)
here the error is 0.03125 which is less then provided epsilon = 0.05
the approximated root 0.640625
⚙️ Code-Based Conceptual Q&A
Q1. Why does the code use eval(func) inside the nested f(x) ?
for example f (x) = 9x + 9, so eval (2)= 18 + 9 = 27 ; so it gives the function
output.
Q2. What would happen if func contains a syntax error or uses a variable name other than x? for
example bisection_method("(4*x**3", 0, 1, 0.05) {first bracket wasn't closed}
A NameError or SyntaxError will occur
Q3. What type of error will occur if the function produces a complex number for any x? for example :
bisection_method("(x**0.5) + 1", -1, 1, 0.05) here for a = −1 ; function becomes f (a) =
1+1
A TypeError or ValueError may occur
Q4. Can this code find multiple roots within the same interval? Why or why not?
No. The bisection method isolates only one root per interval — it assumes a single sign
change. Multiple roots require splitting the interval or scanning for additional sign
changes.
Q5. What is the impact of choosing a very small error_accept on runtime and accuracy?
Smaller tolerances increase iteration count exponentially and runtime grows, but accuracy
improves. However, floating-point precision limits make overly small ε meaningless.
For example error_accept = 0.0001 will take more runtime than error_accept = 0.01
Q6. How could you modify this code to handle functions where the sign change occurs exactly at an
endpoint
(like in the code if f(a)f(b) = 0 {which means a or b is root} the code won't show the root; it will show
“No root or multiple roots present — the bisection method will not work!") how to handle this?
Add a condition before the loop:
f(a) == 0: return a
if f(b) == 0: return b
This directly identifies a root located at an endpoint.
Q7. Define a Python function named bolzano_theorem that takes three inputs — a function, a, and b —
and implements Bolzano's Theorem.
Here is the code:
def bolzano_theorem(function, a, b):
# Bolzano's condition: f(a) * f(b) < 0
if function(a) * function(b) < 0:
print("A root exists in the interval (a, b) by Bolzano's Theorem.")
else:
print("Bolzano's Theorem does not guarantee a root in this interval.")
In [ ]:
def bolzano_theorem(function, a, b):
# Bolzano's condition: f(a) * f(b) < 0
if function(a) * function(b) < 0:
print("A root exists in the interval (a, b) by Bolzano's Theorem.")
else:
print("Bolzano's Theorem does not guarantee a root in this interval