python按概率生成隨機數
阿新 • • 發佈:2019-01-26
Talk is cheap, show me the code.
random_demo.py程式碼如下:
# coding: utf-8
import random
def random_index(rate):
"""隨機變數的概率函式"""
#
# 引數rate為list<int>
# 返回概率事件的下標索引
start = 0
index = 0
randnum = random.randint(1, sum(rate))
for index, scope in enumerate(rate):
start += scope
if randnum <= start:
break
return index
def main():
arr = ['red', 'green', 'blue']
rate = [45, 30, 25]
red_times = 0
green_times = 0
blue_times = 0
for i in xrange(10000):
if arr[random_index(rate)] == 'red':
red_times += 1
if arr[random_index(rate)] == 'green' :
green_times += 1
if arr[random_index(rate)] == 'blue':
blue_times += 1
print red_times, green_times, blue_times
if __name__ == '__main__':
main()
列印結果:
$ python random_demo.py
4507 3009 2537
$ python random_demo.py
4586 3055 2485
$ python random_demo.py
4483 2996 2506
$ python random_demo.py
4586 3015 2480
$ python random_demo.py
4513 3057 2415
$ python random_demo.py
4494 3014 2456
$ python random_demo.py
4502 2978 2505
$ python random_demo.py
4475 3041 2528
$ python random_demo.py
4561 3043 2520
$ python random_demo.py
4558 2923 2474
$ python random_demo.py
4536 2957 2535
$ python random_demo.py
4526 2985 2576
$ python random_demo.py
4532 2936 2547
$ python random_demo.py
4420 2908 2447
可以看到結果, 抽中紅綠藍的次數非常接近它們的概率比例45:30:25, 其中random_index(rate)函式為核心程式碼.
OK, Enjoy it~