我有二进制多项式,我代表二进制数。例如
a = 0b10011
b = 0b101
a是x ^ 4 + x + 1,b是x ^ 2 + 1。所以我想要那个
a%b = 2 # 10 as polynomial x
我想问一下,我该怎么办?我认为两个多项式的标准运算%不起作用。
答案 0 :(得分:0)
这里有一个简单的想法,给定一个正常的多项式除法例程,您可以创建一个自定义类来表示二进制多项式,然后只需覆盖(%)运算符,可能是这样的:
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)
正如你所看到的,你正在用字符串构造多项式,调整类以使用二进制数而不应该太难,作为练习留给读者;)