2014-10-03 82 views
2

我被python中的多项式除法卡住了。这是我修改的代码。 while循环无法工作。此代码仅将原始L输出为r。如果我删除while循环,只输出第一次分割的余数。我尝试了很多方法来使它工作,但都失败了。任何建议将不胜感激。谢谢!Python中的多项式的划分

def GetDegree(poly): 
    while poly and poly[-1] == 0: 
     poly.pop() # normalize 
    return len(poly)-1 

def division(p1,p2): 
    d1 = GetDegree(p1) 
    d2 = GetDegree(p2) 
    if d2 < 0 or d1<0: 
     raise ZeroDivisionError 
    if d1 > d2: 
     S,L = p2,p1#obtain S with lower degree, L with higher degree 
    else: 
     S,L = p1,p2 
    d1 = GetDegree(L) 
    d2 = GetDegree(S) 
    while d1>0: 
      q = [0]*d1 
     d = [0]*(d1 - d2) + S#shift short towards right by d1-d2 
     mult = q[d1 - d2] = L[-1]/float(d[-1])#get the result by dividing the first term of the dividend by the highest term of the divisor 
     d = [coef*mult for coef in d]#multiply the above result by short 
     L = [fabs(coefL - coefd) for coefL, coefd in zip(L, d)]#return a new long by subtracting long with d 
     d1 = GetDegree(L)#return new d1 
    r = L#return new long and keeping looping for there is no variable left and return as remainder 
    return r 

我想输入任何随机多项式进行计算。但是,当我修改它时,结果仍然不正确。这是我跑的测试:num:[2,1,1,1] den:[1,1,2]。打印结果是:报价:[0.25,0.5],rem:[1.75,0.25]。 下面是我修改了输入的情况下,基于从PM 2Ring答案代码:

def normalize(poly): 
     while poly and poly[-1] == 0: 
      poly.pop() 
     if poly == []: 
      poly.append(0) 


    def poly_divmod(num, den): 
     #Create normalized copies of the args 
     num = num[:] 
     normalize(num) 
     den = den[:] 
     normalize(den) 

     if len(num) >= len(den): 
      #Shift den towards right so it's the same degree as num 
      shiftlen = len(num) - len(den) 
      den = [0] * shiftlen + den 
     else: 
      return [0], num 

     quot = [] 
     divisor = float(den[-1]) 
     for i in range(shiftlen + 1): 
      #Get the next coefficient of the quotient. 
      mult = num[-1]/divisor 
      quot = [mult] + quot 

      #Subtract mult * den from num, but don't bother if mult == 0 
      #Note that when i==0, mult!=0; so quot is automatically normalized. 
      if mult != 0: 
       d = [mult * u for u in den] 
       num = [u - v for u, v in zip(num, d)] 

      num.pop() 
      den.pop(0) 

     normalize(num) 
     return quot, num 


    def test(num, den): 
     print ("%s/%s ->" % (num, den)) 
     q, r = poly_divmod(num, den) 
     print ("quot: %s, rem: %s\n" % (q, r)) 
     return q, r 


    def main(): 
     degree = int(input('Enter the degree of your polynomial 1:')) 
     num = [] 
     for i in range (0,degree+1): 
      coefficient = int(input('Enter the coefficient for x^ %i ? ' %i)) 
      num.append(coefficient) 
     degree = int(input('Enter the degree of your polynomial 2:')) 
     den = [] 
     for i in range (0,degree+1): 
      coefficient = int(input('Enter the coefficient for x^ %i ? ' %i)) 
      den.append(coefficient) 
     test(num, den) 



    if __name__ == '__main__': 
     main() 
+0

考虑'聚= [1,2, 0,3,0]'。在开始时,0会弹出,但在下一次迭代中,poly和poly [-1] == 0将计算为false,因此循环终止。但是,程度计算不正确。试试'for'循环。 – 2014-10-03 04:00:00

+0

谢谢。我改变了“而poly和poly [-1] == 0:”to“while poly [-1] == 0:”但是我担心在这种情况下它不是问题。例如P1:[1,2,1]; P2 [2,1,2]。它永远运行。 – Orangeblue 2014-10-03 05:15:46

+0

是的,这不是正确的方式。试试这个'len(p)-p.count(0)'或者使用list comprehension len([x for x in p if x!= 0])或lambda函数 – 2014-10-03 05:32:43

回答

0

我稍加修改你的代码,所以现在它返回商和余数。

FWIW,这将是相当容易的创建一个多项式类,然后你可以做使用标准运算符和函数多项式算法...

#! /usr/bin/env python 

''' Polynomial long division 

From http://stackoverflow.com/questions/26173058/division-of-polynomials-in-python 

A polynomial is represented by a list of its coefficients, eg 
5*x**3 + 4*x**2 + 1 -> [1, 0, 4, 5] 

Modified by PM 2Ring 2014.10.03 
''' 

def normalize(poly): 
    while poly and poly[-1] == 0: 
     poly.pop() 
    if poly == []: 
     poly.append(0) 


def poly_divmod(num, den): 
    #Create normalized copies of the args 
    num = num[:] 
    normalize(num) 
    den = den[:] 
    normalize(den) 

    if len(num) >= len(den): 
     #Shift den towards right so it's the same degree as num 
     shiftlen = len(num) - len(den) 
     den = [0] * shiftlen + den 
    else: 
     return [0], num 

    quot = [] 
    divisor = float(den[-1]) 
    for i in xrange(shiftlen + 1): 
     #Get the next coefficient of the quotient. 
     mult = num[-1]/divisor 
     quot = [mult] + quot 

     #Subtract mult * den from num, but don't bother if mult == 0 
     #Note that when i==0, mult!=0; so quot is automatically normalized. 
     if mult != 0: 
      d = [mult * u for u in den] 
      num = [u - v for u, v in zip(num, d)] 

     num.pop() 
     den.pop(0) 

    normalize(num) 
    return quot, num 


def test(num, den): 
    print "%s/%s ->" % (num, den) 
    q, r = poly_divmod(num, den) 
    print "quot: %s, rem: %s\n" % (q, r) 
    return q, r 


def main(): 
    num = [1, 5, 10, 10, 5, 1] 
    den = [1, 2, 1] 
    test(num, den) 

    num = [5, 16, 10, 22, 7, 11, 1, 3] 
    den = [1, 2, 1, 3] 

    quot = [5, 1, 3, 0, 1] 
    rem = [0, 5] 

    q, r = test(num, den) 
    assert quot == q 
    assert rem == r 


if __name__ == '__main__': 
    main() 
+0

嗨,非常感谢您的帮助!我想输入任何随机多项式进行计算。但是,当我修改它时,结果仍然不正确。这是我跑的测试:num:[2,1,1,1] den:[1,1,2]。打印结果是:报价:[0.25,0.5],rem:[1.75,0.25]。 – Orangeblue 2014-10-04 01:53:20

+0

代码只是假设运行多项式的所有加法/子/多/除法操作的所有代码的一部分。我有多项式类。 – Orangeblue 2014-10-04 01:58:54

+0

你让我担心了一会儿,Orangeblue!但我只是检查它,它*是*正确的。我通过在6年前写的多项式类中进行分割来验证它,并验证num == quot * den + rem。为了仔细检查我的保利班不是越野车,我还用铅笔和纸做了这个部门。 (x 3 + x 2 + x + 2)/(2x 2 + x + 1)= 0.5x + 0.25,其余为0.25x + 1.75。 – 2014-10-04 06:07:45

0
from sympy import Symbol 
from sympy import div 

x = Symbol('x') 

def Poly(p,mod): 
    q,r = div(p,mod,x) #quotient and remainder polynomial division by modulus mod 
    return r.as_poly(x,domain='GF(2)') #Z_2 

m = x**8 + x**4 + x**3 + x + 1 
p = x**6 + x**5 + x + 1 
print Poly(p*p, m) 
+0

嗨ZeldasLizard。你能否扩大你的答案,并描述你改变了什么,为什么,以及它如何帮助提问者?谢谢!旁注:要格式化代码,请选择代码并按下'CRTL + K' – DatRid 2014-10-09 15:41:12