您现在的位置是:网站首页> 编程资料编程资料

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

2023-05-26 340人已围观

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

求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(, {4: 20440, 5: 24462, 8: 4305, 6: 20427, 2: 4499, 3: 11905, 7: 11794, 1: 1010, 0: 84, 9: 963, 10: 111}) '''

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

-六神源码网