如何用随机变量(字母)计算微分。(详情见下文)

How to calculate differentiation with random variables(letters).(details below)

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))

我的代码如下所示,我得到了下面的预期输出。

60*x**2 + 96*x
2*x
-cos(x)

但是如果我测试这个:

print(differentiate("z**5 + 4*z**4 + 3*z**2 + 5", 3))

print(differentiate("z**2", 1))
print(differentiate('sin(z)', 3))

这些输出变成了0,这个要随机字母做区分怎么办?

您可以使用不带参数的 .diff() 来区分单个自由符号:

In [4]: x = Symbol('x')                                                                                                           

In [5]: cos(x).diff()                                                                                                             
Out[5]: -sin(x)

In [6]: S(1).diff()                                                                                                               
Out[6]: 0

如果有多个空闲符号,那么这将失败:

In [7]: y = Symbol('y')                                                                                                           

In [8]: (x*y).diff()                                                                                                              
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-0d2ee58d5fd8> in <module>
----> 1 (x*y).diff()

~/current/sympy/sympy/sympy/core/expr.py in diff(self, *symbols, **assumptions)
   3350     def diff(self, *symbols, **assumptions):
   3351         assumptions.setdefault("evaluate", True)
-> 3352         return Derivative(self, *symbols, **assumptions)
   3353 
   3354     ###########################################################################

~/current/sympy/sympy/sympy/core/function.py in __new__(cls, expr, *variables, **kwargs)
   1262                         to differentiate %s''' % expr))
   1263                 else:
-> 1264                     raise ValueError(filldedent('''
   1265                         Since there is more than one variable in the
   1266                         expression, the variable(s) of differentiation

ValueError: 
Since there is more than one variable in the expression, the
variable(s) of differentiation must be supplied to differentiate x*y

如果你的表达式是单变量的,你想微分一次,那么Oscar已经给出了解决方案。如果它是单变量的并且你想微分任意次数(你函数的n)那么你应该先找到空闲符号然后用它来微分:

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

如果你想处理多变量表达式,你的函数要么必须选择一个随机的自由符号,例如random.choice(free),或将其作为函数输入接受。