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
Asked
Active
Viewed 2,000 times
2 Answers
0
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))

Code_Man
- 1
- 1