Python – Sympy diff() gives incorrect results whenever I set the symbol to real

Sympy diff() gives incorrect results whenever I set the symbol to real… here is a solution to the problem.

Sympy diff() gives incorrect results whenever I set the symbol to real

I

don’t understand why diff() seems to think of it as a constant when I set the symbol to real :

>>> t = sympify("x^2")
>>> x = Symbol('x')
>>> diff(t,x)
2*x
>>> x1=Symbol('x',real=True)
>>> diff(t,x1)
0

Solution

The problem is that the variable x and variable x1 in t are not considered the same due to the “real” property of x1. Thus, in differentiation, the x1 variable is treated as a constant, producing 0.

If you plan to solve this problem using a real variable, you can define an expression using the real variable x.

>>> x = Symbol('x', real=True)
>>> t = sympify('x^2', locals={'x': x})
>>> diff(t, x)
2*x

You can also call locals() instead of using locals Keyword arguments pass explicit dictionaries. Pulling in all the entire local symbol table as one dict using locals=locals(), which can be useful if you have many Symbol variables.

Related Problems and Solutions