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
a+b/2
which is equivalent to
a+(b/2)
but you need
(a+b)/2
. Statement
if (fm == 0):
this statement would probably never run because it is hard to get that close to a root for a few iterations.
Instead, use
if (abs(fm<p)):
Modified code
def bisection(n = 250, p = 10**-6):
# 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)
for i in range(1, n+1):
m = (a + b)/2
x = m
fm = eval(fx)
if(fm * fa < 0):
a = a
b = m
elif (fm * fa > 0):
a = m
b = b
elif (abs(fm<p)):
return m
print(bisection())
Output:
f(x) = x - 1
Boundary A: 0
Boundary B: 3
1.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.