网络编程
位置:首页>> 网络编程>> Python编程>> python实现0到1之间的随机数方式

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

作者:会python的雨哥  发布时间:2023-08-06 17:14:50 

标签:python,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次实验每一个随机变量出现的次数  重复10次实验得到10个随机变量表示每次实验生成的10个随机数代表正面向上的次数
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=sorted(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之间的随机数方式

来源:https://blog.csdn.net/yugemiren/article/details/115124113

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com