[英]Creating Polynomial Class Python Only
我一直在研究包含def __mul__(self, other)
, def __rmul__(self, other)
和def derivative(self)
的多項式類,但是無濟於事。 有人可以告訴我如何做嗎? 注意,self和other的系數的長度可以不同。 到目前為止,我有這個:
class Polynomial(object):
def __init__(self, coeffs):
# if coeffs == [2,-3,5]: 2x**2-3*x+5
self.coeffs = coeffs
def almostEqual(d1, d2):
epsilon = 0.000001
return abs(d1 - d2) < epsilon
def firstNonZeroCoeff(self, coeffs):
coeffs = self.coeffs
for num in xrange(len(coeffs)): #loop through all coeffs
if coeffs[num]!=0: #check if is 0
return coeffs[num]
def degree(self):
return len(self.coeffs)-1
def coeff(self, power):
return self.coeffs[self.degree()-power]
def evalAt(self, x):
return sum([self.coeff(power)*x**power
for power in xrange(self.degree()+1)])
def __add__(self, other):
# First, made both coefficent lists the same length by nondestructively
# adding 0's to the front of the shorter one
(coeffs1, coeffs2) = (self.coeffs, other.coeffs)
if (len(coeffs1) > len(coeffs2)):
(coeffs1, coeffs2) = (coeffs2, coeffs1)
# Now, coeffs1 is shorter, so add 0's to its front
coeffs1 = [0]*(len(coeffs2)-len(coeffs1)) + coeffs1
# Now they are the same length, so add them to get the new coefficients
coeffs = [coeffs1[i] + coeffs2[i] for i in xrange(len(coeffs1))]
# And create the new Polynomial instance with these new coefficients
return Polynomial(coeffs)
非常感謝!
兩個多項式的乘法將是一個嵌套循環。 對於P1中的每個項,您需要將其系數乘以所有P2的系數。 然后添加所有中間結果。 您可以僅出於乘法的目的而創建中間多項式。 然后將它們全部加在一起。
有一個很好的工作實例這里
首先使其正常運行,然后進行任何優化。 祝好運
也許不是最漂亮的實現,但似乎可行
def derivative(self):
# Copy coefficeints to a new array
der = list(self.coeffs)
# (ax^n)' = (n)ax^(n-1)
# 1. ax^n -> ax^(n-1)
print der
der.pop(0)
print der
# 2. ax^(n-1) -> (n)ax^(n-1)
for n in range(1,self.degree()+1):
der[n-1] *= n
return Polynomial(der)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.