I have a simple differentiation function
def differentiate(func, num) -> float:
x = num
h = 0.000000001
der = (func(x h)-func(x))/h
return round(der,4)
print(differentiate(lambda x: x 5,10))
Which gives the expected output of 1.0 But I want to make the func argument such that it only needs the expression to be in the form of a string. For example:
print(differentiate('x 5', 10))
Is this possible to do? Preferably without the help of modules.
CodePudding user response:
It depends whether x is always your variable. If it is the case, then you can use the eval function of python which parses your string and evaluate it as a python expression:
def differentiate(func_x, num) -> float:
x = num
h = 0.000000001
func = lambda x: eval(func_x)
der = (func(x h)-func(x))/h
return round(der,4)
print(differentiate('x 5', 10))
>>> 1.0
Edit: As Serge Ballesta pointed out below, the eval function may have security issues as it allows uncontrolled execution at run time, i.e. it will execute any piece of code given in input, so only use it if you can trust the input of your function.
