how to generate integer inter arrival times using random.expovariate() in python

眉间皱痕 提交于 2019-12-12 12:27:09

问题


In python random module, the expovariate() function generates floating point numbers which can be used to model inter-arrival times of a Poisson process. How do I make use of this to generate integer times between arrival instead of floating point numbers?


回答1:


jonrsharpe already kind of mentioned it, you can just let the function generate floating point numbers, and convert the output to integers yourself using int()

This

>>> import random
>>> [random.expovariate(0.2) for i in range(10)]
[7.3965169407177465, 6.950770519458953, 9.690677483221426, 2.1903490679843927, 15.769487400856976, 3.508366058170216, 2.1922982271553155, 2.591955678743926, 7.791150855029359, 22.180358323964935]

Should then be typed as

>>> import random
>>> [int(random.expovariate(0.2)) for i in range(10)]
[0, 10, 5, 15, 4, 0, 0, 4, 5, 4]

Another example

>>> import random
>>> [int(random.expovariate(0.001)) for i in range(10)]
[435, 64, 575, 2147, 1233, 1630, 1128, 899, 180, 1190]

The examples above use list comprehension to generate multiple results in one line. Can of course be reduced to

>>> import random
>>> int(random.expovariate(0.1)
5

Note that if you pass a higher number to .expovariate() you are more likely to get smaller floating points as result, and when using int() to convert the floats to integers, numbers that are between 0 and 1 will get converted to 0.



来源:https://stackoverflow.com/questions/24242325/how-to-generate-integer-inter-arrival-times-using-random-expovariate-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!