0
def func(x): 
    return x*x*x - x*x + 2

# Prints root of func(x) 
# with error of EPSILON 
def bisection(a,b): 

    if (func(a) * func(b) >= 0): 
        print("You have not assumed right a and b\n") 
        return

    c = a 
    while ((b-a) >= 0.01): 

        # Find middle point 
        c = (a+b)/2

        # Check if middle point is root 
        if (func(c) == 0.0): 
            break

        # Decide the side to repeat the steps 
        if (func(c)*func(a) < 0): 
            b = c 
        else: 
            a = c 

    print("The value of root is : ","%.4f"%c) 

in the above code, I want to get the equation from user as input, here I use xxx - x*x + 2, but I want to get an equation from user input instead of it and use that on the function func(x)

Fred Larson
  • 60,987
  • 18
  • 112
  • 174

2 Answers2

2

If ths code is for academic purposes and you don't want to involve third party libraries, the eval() function in Python is built just for this. You can create a function which evaluates a string expression expr for a value x as such:

def func(expr, x):
    return eval(expr)

input_expr = input('Enter an expression in x: ')
val = 5
print(func(input_expr, val))

Input: x*x*x - x*x + 2

Output: 102

eval() treats the string passed to it as a right hand side expression and evaluates it. So, when the user-input string 'x*x*x - x*x + 2' is passed to the function, the statement return eval('x*x*x - x*x + 2') is equivalent to return x*x*x-x*x+2.

Note that this means there must be a variable x in scope, which we handle by wrapping the eval() function in the function eval_expr().

A problem would arise however, if the user input something like y*y*y+y*y-2 as y isn't declared in the scope. If you need to handle such cases, then you would need to write additional code that converts the input string by replacing any alphabetical character in it to x.

It should be noted that eval generally isn't considered safe, and if this code is not for academic purposes and needs to be safe, you should consider using python libraries like numexpr or pyparsing. numexpr should be fairly easy to use and would suffice for your application.

Aayush Mahajan
  • 3,856
  • 6
  • 25
  • 32
0

Just add it as an argument:

def bisection(func, a, b): 

    if (func(a) * func(b) >= 0): 
        print("You have not assumed right a and b\n") 
        return

    c = a 
    while ((b-a) >= 0.01): 

        # Find middle point 
        c = (a+b)/2

        # Check if middle point is root 
        if (func(c) == 0.0): 
            break

        # Decide the side to repeat the steps 
        if (func(c)*func(a) < 0): 
            b = c 
        else: 
            a = c 

    print("The value of root is : ","%.4f"%c) 
Tarifazo
  • 4,118
  • 1
  • 9
  • 22