我想在 galois 场(GF4)上使用 numpy 数组。所以,我将 GF4 类设置为数组元素。它适用于数组+整数计算,但不适用于数组+数组计算。
import numpy
class GF4(object):
"""class for galois field"""
def __init__(self, number):
self.number = number
self.__addL__ = ((0,1,2,3),(1,0,3,2),(2,3,0,1),(3,2,1,0))
self.__mulL__ = ((0,0,0,0),(0,1,2,3),(0,2,3,1),(0,3,1,2))
def __add__(self, x):
return self.__addL__[self.number][x]
def __mul__(self, x):
return self.__mulL__[self.number][x]
def __sub__(self, x):
return self.__addL__[self.number][x]
def __div__(self, x):
return self.__mulL__[self.number][x]
def __repr__(self):
return str(self.number)
a = numpy.array([GF4(numpy.random.randint(4)) for i in range(18)]).reshape(3,6)
b = numpy.array([GF4(numpy.random.randint(4)) for i in range(18)]).reshape(3,6)
""""
In [261]: a
Out[261]:
array([[1, 1, 2, 0, 2, 1],
[0, 3, 1, 0, 3, 1],
[1, 2, 0, 3, 2, 1]], dtype=object)
In [262]: b
Out[262]:
array([[0, 0, 3, 1, 0, 0],
[0, 1, 0, 1, 1, 1],
[3, 2, 2, 0, 2, 0]], dtype=object)
In [263]: a+1
Out[263]:
array([[0, 0, 3, 1, 3, 0],
[1, 2, 0, 1, 2, 0],
[0, 3, 1, 2, 3, 0]], dtype=object)
In [264]: a+b
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-264-f1d53b280433> in <module>()
----> 1 a+b
<ipython-input-260-0679b73b59a4> in __add__(self, x)
8 self.__mulL__ = ((0,0,0,0),(0,1,2,3),(0,2,3,1),(0,3,1,2))
9 def __add__(self, x):
---> 10 return self.__addL__[self.number][x]
11 def __mul__(self, x):
12 return self.__mulL__[self.number][x]
TypeError: tuple indices must be integers, not GF4
"""
但它也适用于数组和数组*整数计算。
"""
In [265]: a+b*1
Out[265]:
array([[1, 1, 1, 1, 2, 1],
[0, 2, 1, 1, 2, 0],
[2, 0, 2, 3, 0, 1]], dtype=object)
"""
我应该如何更正以下代码?我想使用我的类 GF4。