给定多项式函数作为字符串,return一阶导数作为字符串
Given a polynomial function as a string, return the first derivative as a string
我正在尝试创建一个简单的导数计算器函数,它将多项式函数作为字符串,returns 一阶导数作为另一个字符串。我是初学者,完全不知道如何开始。
def derivative(str):
derivative("3*x^2 + 4*x - 22") # Should return 6*x^1 + 4*x^0 - 0
如果有人能帮助我开始这个,我将不胜感激!
Python 的符号库 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
负责将 ^
转换为幂。
这里有一些示例代码可以帮助您开始和试验。
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)"))
输出:
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)
我正在尝试创建一个简单的导数计算器函数,它将多项式函数作为字符串,returns 一阶导数作为另一个字符串。我是初学者,完全不知道如何开始。
def derivative(str):
derivative("3*x^2 + 4*x - 22") # Should return 6*x^1 + 4*x^0 - 0
如果有人能帮助我开始这个,我将不胜感激!
Python 的符号库 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
负责将 ^
转换为幂。
这里有一些示例代码可以帮助您开始和试验。
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)"))
输出:
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)