python - 二进制多项式模 - Python
问题描述
我有二进制多项式,我将其表示为二进制数。例如
a = 0b10011
b = 0b101
a 是 x^4+x+1,b 是 x^2+1。所以我想要那个
a%b = 2 # 10 as polynomial x
我想问一下,我该怎么做?我认为两个多项式的标准运算 % 不起作用。
解决方案
这是一个简单的想法,给定一个正常的多项式除法例程,您可以创建一个自定义类来表示二元多项式,然后重写 (%) 运算符,可能是这样的:
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)
如您所见,您正在用字符串构造多项式,调整类以使用二进制数而不应该太难,留给读者作为练习;)
推荐阅读
- typescript - 如何使函数基于具有子属性的数组推断类型?
- java - 需要将用户输入存储到 arrayList 并保存到 txt 文件,以便能够在请求后拉回
- android - 如何解决:Room DAO LiveData 在快速后台处理然后恢复应用程序后停止在整个应用程序中发射
- python - 将时间增量转换为天数的 float64
- python - 一行for循环将元素添加到Python中的列表
- queue - 如何在 AnyLogic 中为服务定义排队规则?
- java - java中toString函数的问题(使用局部变量)
- vue.js - Vuetify 在现有组件中使用字体很棒的图标
- html - Perl: 不能使用 'defined(%hash)'
- python - 如何在 fit_generator 中为 3D 数据赋予 class_weight?