05.森林火灾模型
""" 森林火灾模型: "森林"最初只是一个空的N×N网格。每个周期在网格上随机选择一个格点。 如果该格点为空,那么就以概率 g 在那里种上一棵树。 如果该格点上已经有树,那么闪电会以概率(1-g)击中该格点。 如果该格点有一棵树,那么树会着火,火势会蔓延到所有连接到该格点的有树的格点。 """ import numpy as np from random import randint, uniform from collections import Counter import matplotlib.pyplot as plt def forest_fire_model(grid, g): i, j = randint(0, len(grid) - 1), randint(0, len(grid) - 1) p = uniform(0, 1) if not grid[i][j] and p <= g: grid[i][j] = 1 if grid[i][j] and p <= 1 - g: grid[i][j] = 0 if j >= 1: grid[i][j - 1] = 0 if i >= 1: grid[i - 1][j] = 0 if i <= len(grid) - 2: grid[i + 1][j] = 0 if j <= len(grid) - 2: grid[i][j + 1] = 0 return grid if __name__ == "__main__": grid = np.zeros((10, 10), dtype=np.int) # tree_num = [] for i in range(100000): grid = forest_fire_model(grid, 0.6) # 统计数组中某个元素的个数的两种方法 # tree = Counter(grid.flat)[1] # tree = np.sum(grid == 1) # tree_num.append(tree) plt.imshow(grid) plt.show()