Python:循环未给出所需结果

2024-06-07 23:06:57 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着写一个代码来模拟一个捕食者和猎物的情况,从一个低的捕食者种群和高的猎物种群开始。随着时间的推移,捕食者的数量不断增加,而被捕食者的数量不断减少,直到被捕食者的数量太少而无法维持捕食者的数量。捕食者种群死亡,然后被捕食的种群能够重新种群。当两个种群中的一个达到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未定义。你知道吗


Tags: 函数代码数量情况plt种群simulate捕食者
2条回答

如果我用初始总体初始化绘图数据,对总体使用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)

所以你看了你的过程/计算,它似乎是正确的,但你看你的结果,这是有趣的。打印计数时你会注意到一件事。。。你知道吗

print predatorI, preyI

在现实世界中,有些捕食者和猎物是没有意义的。你在试图模拟现实世界。你所有的参数可能都基于整体,而不是分数。所以你决定在你的模拟中不能有任何分数生物,你只在人口增长计算后处理整数生物。。。 enter image description here


函数返回计数向量。如果要将plotting语句移到函数外部,则需要将函数的返回值指定给名称,然后使用它们进行打印。你知道吗

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-objectshttps://docs.python.org/3/reference/executionmodel.html#naming-and-binding

你可能需要定期阅读,因为你使用的语言更多。你知道吗

相关问题 更多 >

    热门问题