python实现0到1之间的随机数方式

2022-07-18 11:43:52

目录求0到1之间的随机数生成0-1之间随机数模拟抛硬币问题求0到1之间的随机数使用random模块中的random()函数,作用就是返回一个[0,1)之间的随机数。importrandomprin...

目录
求0到1之间的随机数
生成0-1之间随机数 模拟抛硬币问题

求0到1之间的随机数

使用random模块中的random()函数,作用就是返回一个[0,1)之间的随机数。

import random
print(random.random())

生成0-1之间随机数 模拟抛硬币问题

import random
def count_heads(n):
    heads=0
    for i in range(n):
        if random.random()<=0.5:
            heads+=1
    return heads
#使用字典记录100000次实验js每一个随机变量出现的次数  重复10次实验得到10个随机变量表示每次实验生成的10个随机数代表正面向http://www.cppcns.com上的次数
import collections
d=collections.defaultdict(int)
for i in range(100000):
    rv_head=count_heads(10)
    d[rv_head]+=1
print(d)
#绘制字典
import matplotlib.pyplot as plt
lists=sowww.cppcns.comrted(d.items())#排序
x,y=zip(*lists)
plt.plot(x,y)
plt.show()

'''结果
defaultdict(<class 'int'>, {4: 20440, 5: 24462, 8: 4305, 6: 20427, 2: 4499, 3: 11905, 7: 11794, 1: 1010, 0: 84, 9: 963, 10: 111})
'''

python实现0到1之间的随机数方式

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。