首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >绘图行列式概率

绘图行列式概率
EN

Code Review用户
提问于 2022-08-23 16:18:14
回答 1查看 37关注 0票数 1

这是一个有趣的练习,它试图回答以下问题:如果从方阵中随机选取的元素从0到9,它更像是行列式是偶数还是奇数?

我很确定有不同的方法来优化这段代码。我首先想到的是只使用发电机(也许?)而不使用for循环来填充值。

代码语言:javascript
复制
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()

欢迎所有建议:

EN

回答 1

Code Review用户

回答已采纳

发布于 2022-08-24 01:03:23

您关心的n实际上不是4,而是4**2 = 16。

不要在Numpy上下文中使用lists、itertoolsfor循环。

不要在本例中使用np.where;您可以单独用% 2替换整个操作。

当存在Numpy等价物时,不要使用math.*方法。

别连在一起。相反,只需在预先分配的数组上使用片。

当您reshape到您的matrix时,将其中一个维度保留为-1。

建议

填充步骤可能看起来像

代码语言:javascript
复制
side = round(np.ceil(np.sqrt(len(determinants))))
filled = np.empty(side**2)
filled[:len(determinants)] = determinants
filled[len(determinants):] = -1

但是您的操作将始终是一个完美的平方,所以只需删除它,只留下与原始代码相同的代码:

代码语言:javascript
复制
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()

输出

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/279088

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档