[英]generating a random number everytime in a loop in python
I am trying to simulate blobs reproducing and dying and every blob has a reproduction- and death chance.我正在尝试模拟斑点的繁殖和死亡,每个斑点都有繁殖和死亡的机会。 Every time in a loop it is supposed to generate a random rumber to see if the death and birth rate is bigger than the random number, if yes, create or delete a blob.
每次在一个循环中它应该生成一个随机数以查看死亡率和出生率是否大于随机数,如果是,则创建或删除一个 blob。 every blob is stored in a list blobs.
每个 blob 都存储在列表 blob 中。
THe problem is that it seems to generate 1 number for all blobs so eiter no one dies or everyone dies at once, but i want different randoms for each blob.问题是它似乎为所有 blob 生成 1 个数字,所以要么没有人死亡,要么每个人都同时死亡,但我希望每个 blob 有不同的随机数。 For example reproduction -and deathchance are 0.5.
例如繁殖和死亡的机会是 0.5。
for blob in blobs:
if blob.reproduce_chance > random.uniform(0,1):
blobs.append(blob)
if blob.death_chance > random.uniform(0,1):
blobs.pop(blobs.index(blob))
import random
variation = 0
for blob in range(10):
if 0.5 > random.uniform(0,1):
print("New born at blob", blob)
variation += 1
if 0.5 > random.uniform(0,1):
print("Death at blob", blob)
variation -= 1
print("Blob count change:", variation)
Output: Output:
Death at blob 1
New born at blob 2
Death at blob 2
New born at blob 4
Death at blob 4
New born at blob 5
Death at blob 5
New born at blob 6
Death at blob 6
New born at blob 7
New born at blob 8
Blob count change: 1
So the problem is not with the random number generator.所以问题不在于随机数生成器。 As said in the comments, it may be due to changing a list while iterating over it.
正如评论中所说,这可能是由于在迭代列表时更改了列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.