1

I have this line of code that finds the root of a function using the Bisection Method. How can I turn this into a recursive function? It needs to output the root of the function.

a=float(input())
b=float(input())
c=float(input())
d=((a)**2)-c
e=((b)**2)-c
if d>0 and e>0:
   print ("Error")
if d<0 and e<0:
   print ("Error")
f=abs(a-b)
while f>(10**-5):
    d=(a**2)-c
    e=(b**2)-c
    g=(a+b)/2
    h=(g**2)-c
    if (d*h)>=0:
      a=g
    else:
      b=g
    f=abs(a-b)
print (a,b, "or", ((a+b)/2))

Thanks in advance!

I tried this: (But it just kept on returning Error and None)

a=float(input())
b=float(input())
c=float(input())
def f(x):
    return (x**2)-c
def bisect(a,b,c):
    if f(a)*f(b)>0:
        print ("Error")
    else:
        midpoint=(a+b)/2
            if f(midpoint)==0 and (b-a)/2<=(10**(-7)):
                return midpoint
            if f(a)*f(midpoint)<0 and (b-a)/2<=(10**(-7)):
                b=midpoint
                return bisect(a,b,c)
            else:
                a=midpoint
                return bisect(a,b,c)
print (bisect(a,b,c))
Fat Cat
  • 63
  • 1
  • 8
  • Why do you want to use recursion? A plain `while` loop is more efficient. Generally, recursion should be avoided in Python unless it's appropriate for the problem domain because unlike some languages, Python cannot optimize tail call recursion. Also, Python's recursion stack has a limited size (which can be adjusted if you really need to), although since that limit is just under 1000 that won't be an issue here. – PM 2Ring Oct 16 '17 at 04:45
  • Just as an example I can look back on in the future since I haven't any idea how to do recursions. – Fat Cat Oct 16 '17 at 04:52
  • I'm looking for the square root of the function. – Fat Cat Oct 16 '17 at 06:50

0 Answers0