这是一个有趣的练习,它试图回答以下问题:如果从方阵中随机选取的元素从0到9,它更像是行列式是偶数还是奇数?
我很确定有不同的方法来优化这段代码。我首先想到的是只使用发电机(也许?)而不使用for循环来填充值。
import itertools
import math
import matplotlib.pyplot as plt
import numpy as np
n = 4
lst = list(itertools.product([0, 1], repeat=n))
algo = list(itertools.product(lst, repeat=n))
determinants = np.abs(np.linalg.det(algo))
determinants = np.where(determinants % 2 == 0, 0, 1)
square = math.ceil((math.sqrt(len(determinants)))) ** 2
# fill with generic value if not a perfect square
for num in range(square - len(determinants)):
determinants = np.append(determinants, -1)
matrix = np.reshape(determinants, (int(math.sqrt(square)), int(math.sqrt(square))))
fig, ax = plt.subplots() # or
ax.imshow(matrix, cmap="Greens")
plt.show()欢迎所有建议:
发布于 2022-08-24 01:03:23
您关心的n实际上不是4,而是4**2 = 16。
不要在Numpy上下文中使用lists、itertools或for循环。
不要在本例中使用np.where;您可以单独用% 2替换整个操作。
当存在Numpy等价物时,不要使用math.*方法。
别连在一起。相反,只需在预先分配的数组上使用片。
当您reshape到您的matrix时,将其中一个维度保留为-1。
填充步骤可能看起来像
side = round(np.ceil(np.sqrt(len(determinants))))
filled = np.empty(side**2)
filled[:len(determinants)] = determinants
filled[len(determinants):] = -1但是您的操作将始终是一个完美的平方,所以只需删除它,只留下与原始代码相同的代码:
import matplotlib.pyplot as plt
import numpy as np
n = 16
lst = np.arange(2**n)
as_bytes = np.stack(
(np.right_shift(lst, n//2), lst),
axis=-1,
).astype(np.uint8)
algo = np.unpackbits(
as_bytes, axis=1,
).reshape((-1, 4, n//4))
determinants = np.abs(np.linalg.det(algo)) % 2
side = round(np.ceil(np.sqrt(len(determinants))))
matrix = determinants.reshape((side, -1))
fig, ax = plt.subplots()
ax.imshow(matrix, cmap="Greens")
plt.show()
https://codereview.stackexchange.com/questions/279088
复制相似问题