【问题标题】:Check if matrix is scalar multiple of another python检查矩阵是否是另一个python的标量倍数
【发布时间】:2020-06-13 15:47:50
【问题描述】:
def scalar_multiple(A,B):    
    #return A is 2*B
A = [[1,0],[0,1]]
B = [[0.5, 0],[0,0.5]]

print(is_scalar_multiple(A,B))

应该打印 2

【问题讨论】:

  • 你尝试了什么?这看起来像是要求某人为您做作业。
  • 我尝试使用 np.matul 将 A 与 B 的倒数相乘(使用 np.linalg.inv),如果结果矩阵是单位矩阵的标量倍数,则通过比较矩阵。
  • 为什么假设B 是可逆的?
  • 我想我并没有这么想。然而,幸运的是,就我而言,它们必然是可逆的。

标签: python numpy


【解决方案1】:
def is_scalar_multiple(A,B):    
    possibleAnswer = A[0][0]/B[0][0] # if they are scalar multiples, this will be the answer
    errorLimit = 10e-10 # our error tolerance, it might be that our floats don't match exactly but according to this error limit they have to match till 11th decimal
    # checking one element at a time
    for i,v in enumerate(A):
        for j in range(len(v)):
            if abs(A[i][j]-(B[i][j]*possibleAnswer))>errorLimit:
                return False # even if one element fails return False
    return possibleAnswer # if everything goes correct return the possible answer
A = [[1,0],[0,1]]
B = [[0.5, 0],[0,0.5]]

print(is_scalar_multiple(A,B))
2.0

如果发现 possibleAnswer 中的分母为 0,这将不起作用

你可以用 if-else 轻松处理

【讨论】:

  • 除以0 怎么样? A[0][0] = B[0][0] = 0.0 很可能是这种情况,但 A 仍然是 B 的标量倍数。
  • 在这些特殊情况下,需要处理
  • 好吧,如果我们知道 'possibleAnswer',我们可以使用更复杂的 numpy 库来检查。
猜你喜欢
  • 2017-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-19
  • 2020-03-20
  • 1970-01-01
相关资源
最近更新 更多