问题
I don't have a problem computing the derivative..it's just that I don't know to handle an entire polynomial in standard algebraic notation :p
回答1:
For computer algebra in Python, sympy is the way to go.
Computing the derivative of a polynomial in sympy is straightforward:
>>> 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
回答2:
The code is not concise, because I want to clearly show each step how it calculates.
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/how-to-input-a-polynomial-in-standard-algebraic-notation-and-get-its-derivative