from sympy.parsing.sympy_parser import parse_expr
import sympy as sp
def differentiate(exp, n):
parse = parse_expr(exp)
diff = sp.diff(parse, 'x' , n)
answer = sp.expand(diff)
return answer
print(differentiate("x**5 + 4*x**4 + 3*x**2 + 5", 3))
print(differentiate("x**2", 1))
print(differentiate('sin(x)', 3))
My code looks like this, and I get the expected output below.
60*x**2 + 96*x
2*x
-cos(x)
But if I test this:
print(differentiate("z**5 + 4*z**4 + 3*z**2 + 5", 3))
print(differentiate("z**2", 1))
print(differentiate('sin(z)', 3))
These outputs become 0
, what should I do for this if I want a random letter to do differentiation?
If your expression is univariate and you want to differentiate once, then Oscar has given the solution. If it is univariate and you want to differentiate an arbitrary number of times (the n
of your function) then you should find the free symbol first and then use it to differentiate:
def differentiate(exp, n):
parse = parse_expr(exp)
free = parse.free_symbols #
assert len(free) == 1 # x is identified
x = free.pop() # as the single free symbol
diff = sp.diff(parse, x , n) #
answer = sp.expand(diff)
return answer
If you want to handle multivariate expressions, your function will either have to pick a random free symbol, e.g. random.choice(free)
, or accept that as a function input.