简体   繁体   English

二进制多项式取模-Python

[英]Binary polynomials modulo - Python

I have binary polynomials, which I represent like binary number. 我有二进制多项式,它表示为二进制数。 For example 例如

a = 0b10011 
b = 0b101

a is x^4+x+1 and b is x^2+1. a是x ^ 4 + x + 1,b是x ^ 2 + 1。 So I want that 所以我想要

a%b = 2 # 10 as polynomial x

I would like to ask, how can I do it? 我想问一下,我该怎么办? I think that standard operation % of two polynomials will not work. 我认为两个多项式的标准运算百分比无效。

Here's a simple idea, given a normal polynomial division routine you could create a custom class to represent binary polynomials and then just override the (%) operator, maybe something like this: 这是一个简单的想法,给定一个普通的多项式除法例程,您可以创建一个表示二进制多项式的自定义类,然后重写(%)运算符,也许是这样的:

from math import fabs


def poly_div(p1, p2):
    def degree(poly):
        while poly and poly[-1] == 0:
            poly.pop()
        return len(poly)-1

    p2_degree = degree(p2)
    p1_degree = degree(p1)

    if p2_degree < 0:
        raise ZeroDivisionError

    if p1_degree >= p2_degree:
        q = [0] * p1_degree
        while p1_degree >= p2_degree:
            d = [0]*(p1_degree - p2_degree) + p2
            mult = q[p1_degree - p2_degree] = p1[-1] / float(d[-1])
            d = [coeff*mult for coeff in d]
            p1 = [fabs(p1_c - p2_c) for p1_c, p2_c in zip(p1, d)]
            p1_degree = degree(p1)
        r = p1
    else:
        q = [0]
        r = p1

    return q, r


class BinPoly:

    def __init__(self, poly):
        self.poly = [int(bit) for bit in list(poly)]

    def __mod__(self, other):
        return poly_div(self.poly, other.poly)


if __name__ == '__main__':
    a = BinPoly('10011')
    b = BinPoly('101')
    print(a%b)

As you can see, you're constructing the polynomials out of string, tweaking the class to use binary numbers instead shouldn't be too hard, left as an exercise to the reader ;) 如您所见,您是在字符串之外构造多项式,调整类以使用二进制数应该不会太难,留给读者练习;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM