如何在标准代数表示法中输入多项式并得到它的导数? (蟒蛇)

时间:2014-02-17 04:45:36

标签: python calculus derivative

我没有计算衍生物的问题..这只是我不知道用标准代数表示法处理整个多项式:p

2 个答案:

答案 0 :(得分:1)

对于Python中的计算机代数,sympy是可行的方法。

在sympy中计算多项式的导数很简单:

>>> import sympy as sp
>>> x = sp.symbols('x')
>>> sp.diff(3*x**4 + 8*x**2 - 3*x + 1)
12*x**3 + 16*x - 3

答案 1 :(得分:0)

代码不简洁,因为我想清楚地显示每一步的计算方法。

import re

def FirstDerivative(poly):
"Given a polynominal, output its first derivative"
rslt = ""
for sign, coef, expo in re.findall("([\+-]?)\s?(\d?)\*?x\*?\*?(\d?)", '+' + poly):
    coef = int(sign + coef)
    if expo == "":
        expo = "1"
    expo = int(expo)

    new_coef = coef * expo
    new_expo = expo - 1
    if new_coef > 0:
        rslt += "+"
    if new_expo == 0:
        rslt += "%d" % (new_coef)
    elif new_expo == 1:
        rslt += "%d*x" % (new_coef)
    else:
        rslt += "%d*x**%d" % (new_coef, new_expo)

if rslt[0] == "+":
    rslt = rslt[1:]
rslt = rslt.replace("+", " + ")
rslt = rslt.replace("-", " - ")
return rslt

s = "-3*x**4 + 8*x**2 - 3*x + 1"
print(FirstDerivative(s))

s = "3*x**5 + 2*x**3 - 3*x + 1"
print(FirstDerivative(s))