import random from matplotlib import pyplot #蒙特卡洛算法 class MTKL: def __init__(self, n, m): self.n = n self.m = m def MC(self): n = self.n m = self.m for i in range(m): # 在(0,1)之间去随机数 x = random.random() y = random.random() if ((x * x * x) - y >= 0): n += 1 return (n / m) def mc(self, n, m): for i in range(m): # 在0,1之间去随机数 x = random.random() y = random.random() if ((x * x * x) - y >= 0): n += 1 s = n / m return (s) def draw_MC(self): xx = [] yy = [] for i in range(self.m): x = random.random() y = random.random() if ((x * x * x) >= y): xx.append(x) yy.append(y) pyplot.plot(xx, yy) pyplot.show() test = MTKL(0, 10000) test.MC() print('结果:') print(test.MC()) print(test.draw_MC())