Python 蒙特卡罗模拟无法识别连通图
我正在写一个蒙特卡罗模拟,计算使n顶点图连接所需的最小有向边数的期望值。它从一个全0邻接矩阵开始,添加一条有向边,然后测试该矩阵,看它是否表示一个连通图。这个过程是循环的,直到构建了一个连通图,然后迭代的次数就是单个试验的样本量。该程序对于小型图似乎是精确的,但一旦图超过10个顶点,就越来越清楚地看到,它会在已构造连通图之后继续添加顶点。本质上,该算法在大型图上停止得不够早 似乎可能的罪魁祸首是断开连接的函数,但我不能完全确定。如有任何建议,将不胜感激Python 蒙特卡罗模拟无法识别连通图,python,algorithm,math,graph,montecarlo,Python,Algorithm,Math,Graph,Montecarlo,我正在写一个蒙特卡罗模拟,计算使n顶点图连接所需的最小有向边数的期望值。它从一个全0邻接矩阵开始,添加一条有向边,然后测试该矩阵,看它是否表示一个连通图。这个过程是循环的,直到构建了一个连通图,然后迭代的次数就是单个试验的样本量。该程序对于小型图似乎是精确的,但一旦图超过10个顶点,就越来越清楚地看到,它会在已构造连通图之后继续添加顶点。本质上,该算法在大型图上停止得不够早 似乎可能的罪魁祸首是断开连接的函数,但我不能完全确定。如有任何建议,将不胜感激 import numpy as np im
import numpy as np
import math
import random
# Randomly adds an edge to the graph by
# choosing a random 0 from the adjecency
# matrix and changing it to a 1.
# @param mat - the list type matrix
# @param k - the dimension of the matrix
def addEdge(mat, k):
flag = False
while flag == False:
colNum = random.randint(0, k-1)
rowNum = random.randint(0, k-1)
if mat[rowNum][colNum] == 0:
mat[rowNum][colNum] = 1
flag = True
# Runs singleTrial multiple times and finds
# the average of their sample sizes
def getExpectedValue(size, trials):
sampleSum = 0.0
flag = True
for i in range(trials):
sample = singleTrial(size)
sampleSum += sample
expectedValue = float(sampleSum/trials)
return expectedValue
# Adds edges to an initially edgeless
# graph UNTIL the graph becomes connected.
def singleTrial(size):
# Create all zero matrix
mat = np.random.randint(0,1,size=(size,size))
sample = 0
flag = True
while flag:
# Uncomment this code to see each matrix that is
# generated in a single trial. Upon viewing it
# is clear that this while loop does not terminate
# early enough.
#print mat
#print "\n"
addEdge(mat, size)
sample += 1
if isConnected(mat, size):
print mat
flag = False
print sample
return sample
# Checks if a given matrix is connected by
# calculating the sum of the number of 1 step
# paths though the number of k step paths
# for every pair of verticies. If this number
# is zero for any pair, then the graph is
# not connected.
def isConnected(A, k):
B = A
for i in range(2, k-1):
B = B + np.linalg.matrix_power(A, i)
if np.prod(B) != 0:
return True
else:
return False
if __name__ == '__main__' :
# Perform 1 trial on an 11 vertex graph
print getExpectedValue(11, 1)
我解决了这个问题。我使用函数numpy.prod(mat)检查矩阵是否包含零,因为它返回矩阵中所有项的乘积。我没有考虑过溢出的可能性。我假设如果numpy.prod的值变得太大(它肯定会这么做),它将重置为零。这会造成许多错误的否定。为什么要使用np.prod(B)而不是(B==0)。any()?这是一个python学校的项目,我的老师更喜欢数学,他建议使用prod()。虽然我已经引起了他的注意,而且已经解决了。我刚开始学习python,所以我不知道any()函数。谢谢你的提示。