如何计算galois域上的numpy数组?

Ryo*_*hii 5 python arrays numpy galois-field

我想在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
"""
Run Code Online (Sandbox Code Playgroud)

但它也适用于数组和数组*整数计算.

"""
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)
"""
Run Code Online (Sandbox Code Playgroud)

我该如何更正以下代码?我想用我的班级GF4.

Jai*_*ime 3

问题是Python不知道当元组xGF4对象时如何索引元组。你可以做这样的事情来解决这个问题:

def __add__(self, x):
    if isinstance(x, GF4):
        x = x.number
    return self.__addL__[self.number][x]
Run Code Online (Sandbox Code Playgroud)

您可能需要注意另一个潜在问题,这解释了为什么您的第三个测试用例有效:当您将 an 添加int到 a时GF4,返回的是 int,而不是GF4。除非这是期望的行为,否则我认为您的代码__add__应该更像是:

def __add__(self, x):
    if isinstance(x, GF4):
        x = x.number
    return GF4(self.__addL__[self.number][x])
Run Code Online (Sandbox Code Playgroud)

您可能需要考虑所有可能性,并决定是否需要构建更多保护措施并抛出一些您自己的错误,例如,如果您尝试将 a 添加float到 a ,则返回应该是什么GF4

  • 老实说,它不是很Pythonic。我认为对于您的特定类来说,更好的选择是[对 int 数字类型进行子类化](http://stackoverflow.com/questions/3238350/subclassing-int-in-python) 并重载运算符。您还可以使用 [ducktyping](http://en.wikipedia.org/wiki/Duck_typing) 来实现您的类,可能带有 try/ except 子句。 (2认同)