I'm attempting to create a simple derivative calculator function that takes a polynomial function as string, and returns the first derivative as another string. I'm a beginner and am completely lost on how to start.
def derivative(str):
derivative("3*x^2 + 4*x - 22") # Should return 6*x^1 + 4*x^0 - 0
If someone could help me get started with this, I would greatly appreciate it!
Python's symbolic library sympy
can take care of converting a string to a symbolic expression and of taking derivatives. Note that Python uses **
for power
, while ^
is only used for the boolean exclusive or. convert_xor
takes care of converting the ^
to a power.
Here is some sample code to get you started and experimenting.
from sympy import sympify, Derivative
from sympy.parsing.sympy_parser import parse_expr, standard_transformations, convert_xor
def derivative(str_expr):
transformations = (standard_transformations + (convert_xor,))
expr = parse_expr(str_expr, transformations=transformations)
return str(Derivative(expr).doit())
print(derivative("3*x^2 + 4*x - 22"))
print(derivative("sin(x/cos(x))"))
print(derivative("exp(asin(x^2)/sqrt(x))"))
print(derivative("LambertW(x)"))
print(derivative("erf(x)"))
Output:
6*x + 4
(x*sin(x)/cos(x)**2 + 1/cos(x))*cos(x/cos(x))
(2*sqrt(x)/sqrt(1 - x**4) - asin(x**2)/(2*x**(3/2)))*exp(asin(x**2)/sqrt(x))
LambertW(x)/(x*(LambertW(x) + 1))
2*exp(-x**2)/sqrt(pi)