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

Kitty ·
更新时间:2024-09-20
· 828 次阅读

目录

求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次实验每一个随机变量出现的次数 重复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

需要 登录 后方可回复, 如果你还没有账号请 注册新账号