如何对函数进行迭代



我正在模拟森林火灾,我的任务之一是绘制树木密度与当前燃烧和空地的密度。我有不同的部分,但我需要帮助将它们组合在一起,因为我不知道如何将代码组合在一起。目前,我有我的初始条件

p, f = 0.5, 0.3
nx, ny = 100, 100
X = np.zeros((ny, nx))
adjacent = ((-1,0), (0,-1), (0, 1), (1,0))
E, T, F = 0, 1, 2
xvalues = [0]
yvalues = [0]

我生成下一帧(火力分布(的函数是

def iterate(X):
Xnew = np.zeros((ny, nx))
for ix in range(1,nx-1):
for iy in range(1,ny-1):
if X[iy,ix] == E and np.random.random() <= p:
Xnew[iy,ix] = T
if X[iy,ix] == T:
Xnew[iy,ix] = T
for dx,dy in adjacent:
if X[iy+dy,ix+dx] == F:
Xnew[iy,ix] = F
else:
if np.random.random() <= f:
Xnew[iy,ix] = F                    
return Xnew
print(Xnew)

我正在努力的一点是如何用上面的材料正确地写出下面的内容,这样我就可以达到Xn,其中n大约是1000

X1 = iterate(X)
X2 = iterate(X1)
X3 = iterate(X2) and so on

并且对于每次迭代计算

num_empty = (Xn == 0).sum()
num_tree = (Xn == 1).sum()
num_fire = (Xn == 2).sum()
density = num_tree/(num_fire+num_empty)
xvalues.append(i)
yvalues.append(density)

print(density)

任何帮助都将不胜感激!

我认为您需要在n int的范围内迭代,而不是"函数";。

i = 0
_X = iteration(X)
num_empty = (_X == 0).sum()
num_tree = (_X == 1).sum()
num_fire = (_X == 2).sum()
density = num_tree / (num_fire + num_empty)
print(i, density)
xvalues.append(i)
yvalues.append(density)
n = 1000
for i in range(1, n):
_X = iteration(_X)
num_empty = (_X == 0).sum()
num_tree = (_X == 1).sum()
num_fire = (_X == 2).sum()
density = num_tree / (num_fire + num_empty)
print(i, density)
xvalues.append(i)
yvalues.append(density)

相关内容

  • 没有找到相关文章

最新更新