0
votes

I am tasked with writing a program to do the bisection method to solve for the sqrt(2) with 6 iterations of the bisection method. Here is my code. I cannot get it to print the values along the way or in the end and I am not sure why.

import math
>>> def f(x):
    return (x**2)-2

>>> def bisect (a,b,n):
    while n < 6:
        c=(a+b)/2
    if f(c) == 0:
        print [('Root is: ', c)]
    elif f(a)*f(b) > 0:
        b=c
        n=(n+1)
        print [('n: ',n,' c: ',c)]
    else:
        a=c
        n=(n+1)
        print [('n: ',n,' c: ',c)]


>>> print bisect (0,1,0)
SyntaxError: invalid syntax
>>> print bisect (0,1,0):

SyntaxError: invalid syntax
>>> 
1

1 Answers

0
votes

I immediately see two issues. First, in Python 3, you need to use parentheses around what you want to print (i.e., print(bisect(0,1,0))). This is what's causing your syntax error. Second, unless your indentation is wrong, your bisect function starts with an infinite loop, since it repeats while n < 6 but never increases n.