Back to SDS/2 Parametric Scripts

 

# Bisection - solve a single variable multinomial expression using the bisection method

# The multinomial must be a string and must be a valid expression for evaluation

 

def solve(s, x, y=1.0):

    return eval(s)

 

def bisection(s, U, L, e=0.00001):

    U, L = map(float, [U, L])

    if solve(s, U) > 0 and solve(s, L) < 0:

        while abs(U - L) > e:

            M = (U+L)/2

            if solve(s, M)*solve(s,U) > 0:

                U = M

            else:

                L = M

            print U, L

        return U,L

    else:

        return "Invalid arguments. f(U) must be > 0 and f(L) must be < 0."

 

if __name__ == '__main__':

    # This enables the script to execute at the windows command prompt

    # Example: C:\>python find_root.py x**2-4 3 0

    """

    import sys

    print sys.argv

    try:

        print bisection(sys.argv[1], float(sys.argv[2]))

    except (IndexError, TypeError):

        print "Usage: Invalid or incorrect number of arguments"

    """

    # To execute at the Python command line:

    # from bisection import bisection

    # bisection('x**2-4', 3, 0, 0.0001)

   

    s = '5*(x**4)-3*(x**3)-x-2000'

    print solve(s, 6.0)

    print

    print bisection(s, 6.0, 4.0)

 

"""

>>>3826.0

 

5.0 4.0

5.0 4.5

4.75 4.5

4.75 4.625

4.6875 4.625

4.65625 4.625

4.640625 4.625

4.6328125 4.625

4.6328125 4.62890625

4.6328125 4.630859375

4.6328125 4.6318359375

4.6328125 4.63232421875

4.6328125 4.63256835938

4.63269042969 4.63256835938

4.63262939453 4.63256835938

4.63262939453 4.63259887695

4.63261413574 4.63259887695

4.63261413574 4.63260650635

(4.6326141357421875, 4.6326065063476563)

>>>

"""