Part A - Bisection Method Write a function called bisection(n, p) that asks the user to enter a mathematical function f(x) and two boundary points in order to solve for r such that f(r) = 0 using bisection method. The function terminates when the solution r is found or when the maximum number of iterations n is reached (default n = 100), whichever occurs first.
def bisection(n = 100, p = 0.0001):
# code goes below
fx = input("f(x) = ")
a = float(input("Boundary A: "))
x = a
fa = eval(fx)
b = float(input("Boundary B: "))
x = b
fb = eval(fx)
i = 0
if (fa * fb >= 0):
print("Bisection method fails")
return
while(i < n):
m = a + b / 2
x = m
fm = eval(fx)
if(fm * fa < 0):
a = a
b = m
if (fm * fb < 0):
a = m
b = b
i = i + 1
if (fm == 0):
return m
pass
When I input: f(x) = x - 1 Boundary A: 0 Boundary B: 3
No answer is printed so I'm very confused?!
There are lots of problems with this code. For some reason you defined p and never passed it again, I assume it stands for epsilon. You defined midpoint as
which is equivalent to
but you need
. Statement
this statement would probably never run because it is hard to get that close to a root for a few iterations.
Instead, use
Modified code
Output: