我没有计算导数的问题,只是我不知道用标准代数记法来处理整个多项式:
发布于 2014-02-17 12:49:33
对于Python语言中的计算机代数,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发布于 2018-06-05 15:06:53
代码并不简洁,因为我想清楚地显示每一步是如何计算的。
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))https://stackoverflow.com/questions/21820947
复制相似问题