种群竞争元胞自动机代码
时间: 2024-02-04 22:10:04 浏览: 165
元胞自动机 代码
5星 · 资源好评率100%
种群竞争元胞自动机是一种模拟生物种群之间相互竞争和演化的计算模型。下面是一个简单的种群竞争元胞自动机的代码示例:
```python
import numpy as np
# 定义元胞自动机的参数
grid_size = 50 # 网格大小
num_iterations = 100 # 迭代次数
num_species = 2 # 物种数量
# 初始化网格
grid = np.zeros((grid_size, grid_size), dtype=int)
# 随机初始化每个细胞的物种
for i in range(grid_size):
for j in range(grid_size):
grid[i, j] = np.random.randint(0, num_species)
# 迭代更新每个细胞的物种
for iteration in range(num_iterations):
new_grid = np.copy(grid)
for i in range(grid_size):
for j in range(grid_size):
# 统计周围细胞的物种分布
species_count = [0] * num_species
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue
ni = (i + dx) % grid_size
nj = (j + dy) % grid_size
species_count[grid[ni, nj]] += 1
# 竞争规则:选择最多的物种作为当前细胞的物种
max_species = np.argmax(species_count)
new_grid[i, j] = max_species
grid = np.copy(new_grid)
# 打印最终的物种分布
species_count = [0] * num_species
for i in range(grid_size):
for j in range(grid_size):
species_count[grid[i, j]] += 1
for species in range(num_species):
print(f"物种 {species}: {species_count[species]} 个细胞")
```
这段代码使用了numpy库来处理网格数据,通过迭代更新每个细胞的物种,根据周围细胞的物种分布进行竞争,并选择最多的物种作为当前细胞的物种。最后打印出最终的物种分布。
阅读全文