Python:循环没有给出期望的结果

时间:2016-11-24 17:13:32

标签: python matplotlib while-loop simulation

所以我正在尝试编写一个模拟捕食者和猎物情况的代码,它开始时捕食者数量很少,猎物数量很高。随着时间的推移,捕食者数量增加,而猎物种群数量减少,直到猎物种群数量太少而无法维持捕食者种群。捕食者群体死亡,然后猎物种群能够重新种群。当两个群体中的一个达到0时,模拟应该停止,在这种情况下,捕食者群体将在模拟的时间内绘制两个群体,直到它停止为止。到目前为止,这是我的代码:

import matplotlib.pyplot as plt

def simulate(initialPred, initialPrey, preyGrowth, predationRate, predShrink, predFedBirthRate):
    preyCounts = []
    predatorCounts = []
    predatorI = initialPred
    preyI = initialPrey
    predator = predatorI
    prey = preyI



    while predator > 0 and prey > 0:

            predator = predatorI * (1 - predShrink + predFedBirthRate * preyI)
            prey = preyI * (1 + preyGrowth - predationRate * predatorI)
            predatorCounts.append(predator)
            preyCounts.append(prey)
            predatorI = predator
            preyI = prey


    plt.plot(predatorCounts, 'r', preyCounts, 'b')
    plt.show()      

    return preyCounts, predatorCounts

simulate(50,1000,0.25,0.01,0.05,0.00002)

它的输出就是这个 :enter image description here

但它应该像这样出来: enter image description here

有人能帮助我吗?

*除此之外,每当我将我的绘图代码放在函数行之后的函数行之外,其值如下所示:

simulate(50,1000,0.25,0.01,0.05,0.00002) 
plt.plot(predatorCounts, 'r', preyCounts, 'b')
plt.show() 

它没有绘制函数中的值,并且predatorCountspreyCounts未定义。

2 个答案:

答案 0 :(得分:1)

所以你看了你的过程/计算,看起来是正确的,但你看看你的结果,这很有趣。打印计数时你注意到的一件事......

print predatorI, preyI

是有一些捕食者和猎物,在现实世界中,它们没有意义。你正试图模拟现实世界。您的所有评分参数可能都是基于整个事情,而不是基于分数的事情。所以你决定在你的模拟中不能有任何小数生物,而你只在人口增长计算后处理整个生命(整数)...... enter image description here

您的函数返回计数向量。如果要将绘图语句移到函数之外,则需要将函数的返回值赋给名称,然后将它们用于绘图。

prey, predator, = simulate(50,1000,0.25,0.01,0.05,0.00002) 
plt.plot(predator, 'r', prey, 'b')
plt.show() 

以下是有关名称,范围,命名空间的文档中的一些内容 https://docs.python.org/3/tutorial/classes.html#a-word-about-names-and-objects https://docs.python.org/3/reference/executionmodel.html#naming-and-binding

您可能需要在使用更多语言时定期阅读它们。

答案 1 :(得分:1)

如果我使用起始种群 初始化您的地图数据,请对群体使用int()截断,我会得到您说你应该使用的情节见:

import matplotlib.pyplot as plt

def simulate(initialPred, initialPrey, preyGrowth, predationRate, predShrink, predFedBirthRate):
    preyCounts = [initialPrey]
    predatorCounts = [initialPred]
    predator = initialPred
    prey = initialPrey

    while predator > 0 and prey > 0:
        predatorScaleFactor = 1.0 - predShrink + predFedBirthRate * prey
        preyScaleFactor = 1.0 + preyGrowth - predationRate * predator
        predator = int(predator * predatorScaleFactor)
        prey = int(prey * preyScaleFactor)
        predatorCounts.append(predator)
        preyCounts.append(prey)

    plt.plot(predatorCounts, 'r', preyCounts, 'b')
    plt.show()

    return preyCounts, predatorCounts

simulate(50, 1000, 0.25, 0.01, 0.05, 0.00002)