'Python Hw, bisection Method
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?!
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
