需要有关使用矩阵进行二进制供电的帮助

时间:2016-03-12 15:10:16

标签: python matrix binary

我正在尝试编写一个程序,可以使用二进制供电来计算2x2矩阵的n次方。我真的很感激帮助。我的问题是代码只适用于2的幂矩阵。

   def binPow(m,n):
    if (n==0): return[[1,0],[0,1]]
    q = binPow(m,n//2)
    square = MatrMult(o,o)
    if (n%2==0):
        return square
    else:
        return MatrMult(m,square)

def MatrMult(o,x):
    o = [[b,c],[e,f]]
    g = [[(b*b)+(c*e),(b*c)+(c*f)],[(e*b)+(f*e),(e*c)+(f*f)]]
    return(g)

b = int(input("Enter A1: ")) 
c = int(input("Enter A2: "))
e = int(input("Enter A3: "))
f = int(input("Enter A4: "))
o = [[b,c],[e,f]]
n = int(input("Enter Power: "))

print(o, "to the power of", n, " is ", binPow(o,n))

1 个答案:

答案 0 :(得分:0)

在Python3中,n/2将产生一个浮点数。 1/20.50.5/20.250.25/20.125等。它永远不会为0,因此if (n==0): ...永远不会执行。要确保n始终是一个整数,请加倍斜杠:q = binPow(m, n//2)。这样,5//2变为2而不是2.5等。您真正的问题是如何将矩阵相乘。您总是对原始矩阵进行平方,因为您没有对给定的参数执行任何操作。我也冒昧地将你的binPow()函数修改为更简单的东西:

def binPow(m,n):
    if (n==0): return[[1,0],[0,1]]
    q = m 
    while n > 1:
        q = MatrMult(m, q)
        n -= 1
    return q

def MatrMult(o,x):
    ((a, b), (c, d)) = o 
    ((e, f), (g, h)) = x 
    g = [[(a*e)+(b*g),(a*f)+(b*h)],[(c*e)+(d*g),(c*f)+(d*h)]]
    return(g)