I am currently working on creating a python script that will do a series of calculations based on the formula entered by the user; however, it is not working as expected?
I have tried the following:
init_printing(use_unicode=True)
x, y = symbols('x y', real = True)
userinput = sympify(input("testinput: "))
x_diff = diff(userinput, x)
print(x_diff)
However, this always returns zero, but when I write the input directly, e.g.
init_printing(use_unicode=True)
x, y = symbols('x y', real = True)
userinput = x**0.5 y
x_diff = diff(userinput, x)
print(x_diff)
It works flawlessly, what am I doing wrong here?
Thanks!
CodePudding user response:
Adding locals
parameter in sympify
function will help you. Here is a working code, based on yours :
from sympy import *
init_printing(use_unicode=True)
x, y = symbols('x y', real = True)
userinput = input("testinput: ")
locals = {'x':x, 'y':y}
sympified = sympify(userinput, locals=locals)
print(f'derivate /x : = \n {diff(sympified, x)} \n derivative / y : \n {diff(sympified, y)}')
Output:
testinput: cos(y) 2*x
derivate /x :
2
derivative /y :
-sin(y)