好吧,所以这里有一些不同的事情,其中一些已被处理,其中一些没有。
第一件事,正如@DYZ指出的那样,你试图将行向量附加到空矩阵。这可以通过重塑空矩阵来解决。
代码也可以通过以下方式大大简化:
import numpy as np def custom_operator(state): dimension = int(input("What are the dimensions of your (square) matrix? Please input a single number:")) elements = list() for x in range(dimension): for y in range(dimension): value = float(input("Matrix element at ({x}, {y}):".format(x=x+1, y=y+1))) elements.append(value) operator = np.matrix(np.resize(elements, (dimension, dimension))) output_state = np.dot(operator, state) return output_state state = np.matrix([[0], [1]]) custom_operator(state)
请注意,我删除了 import math 您没有使用的声明,当您要求维度时,您应该将响应转换为 int 不是漂浮物。
import math
int
也没有必要检查门是否是单一的。无论哪种方式,您仍然返回状态操作的输出。 (除非你真的想知道它是不是。)如果你确实想要,如果尺寸不是2,你当前的检查将失败。更好的检查将是
np.allclose(operator.dot(operator.T.conj()), np.eye(len(dimension)))
但是,鉴于您想要将任何门应用于您的状态,您就知道矩阵的尺寸必须是什么。允许用户指定他们想要将qutrit门应用于量子位状态只会允许他们引入错误。所以更好的代码版本是:
import numpy as np def custom_operator(input_state): dimension, width = input_state.shape if width != 1: error_message = "Input state must be a column vector" raise ValueError(error_message) elements = list() for x in range(dimension): for y in range(dimension): value = float(input("Matrix element at ({x}, {y}):".format(x=x+1, y=y+1))) elements.append(value) operator = np.matrix(np.resize(elements, (dimension, dimension))) output_state = np.dot(operator, input_state) return output_state state = np.matrix([[0], [1]]) custom_operator(state)
此外,如果您想进行这些门模拟,如果您还不知道它们,请务必查看 all_close 和 重塑 。他们会出现很多。
其他人已经指出了为什么你的方法会给你带来那个错误。我将添加另一种方法来创建矩阵。请注意,在您要求输入之前,您将获得用户的尺寸(并且它始终是方形矩阵)。因此,您可以创建一个零矩阵,然后随着用户提供的条目填充它,如下所示:
def customop(qstat): dimensions = input("What are the dimensions of your (square) matrix? Please input a single number: ") matrix = np.zeros([dimensions, dimensions]) for iterator in range(dimensions): for iterator_2 in range(dimensions): matrix[iterator, iterator_2] = float(input("Matrix element at "+str(iterator)+","+str(iterator_2)+": ")) if np.array_equal(np.dot(matrix, matrix.conj().T), np.identity(2)) == True: print(matrix) return np.dot(matrix, qstat) else: print(matrix) print("matrix not unitary, pretending no gate was applied") return qstat qstat = np.matrix([[0],[1]]) customop(qstat)
我用for循环替换了while循环,以便自动处理初始化和递增。
如果我理解正确,确定矩阵维度,附加用户的值,然后调整列表大小并将其转换为矩阵应该工作:
dimension = int(输入(“(方形)矩阵的尺寸是多少?请输入一个数字:”))
ls = [] for y in range(dimension): for x in range(dimension): ls.append(float(input('What value for position ({}, {}): '.format(y+1, x+1)))) np.matrix(np.resize(ls, (dimension, dimension)))
输出:
What are the dimensions of your (square) matrix? Please input a single number: 3 What value for position (1, 1): 1 What value for position (1, 2): 2 What value for position (1, 3): 3 What value for position (2, 1): 1 What value for position (2, 2): 2 What value for position (2, 3): 3 What value for position (3, 1): 1 What value for position (3, 2): 2 What value for position (3, 3): 3 Out[29]: matrix([[ 1., 2., 3.], [ 1., 2., 3.], [ 1., 2., 3.]])