-1

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?!

Ocean
  • 21
  • 4

1 Answers1

0

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
goku
  • 167
  • 10
  • Why is there a (n + 1), could you explain it just a tiny bit? – Ocean May 02 '22 at 06:46
  • In order to get n iterations, you can either say i in range (0, n) or i in range (1, n+1) they're exactly the same for this problem. Note that the lower bound is included and the upper bound is excluded in python. – goku May 02 '22 at 08:02
  • What if Boundary A is larger than Boundary B? for example Boundary A: 1 and Boundary B: 0? – Ocean May 03 '22 at 16:52