python随机数

说一说python生成随机数的方法

使用random模块

1.random.random()方法,这个方法返回一个随机的实数,范围在[0,1)之间

2.random.uniform(a,b)方法,生成a,b之间的一个随机浮点数

3.random.randint(a,b)方法,生成指定范围内的整数

4.random.randrange(a,b,n)方法,在a,b范围内,按n递增的集合中随机选择一个数

选择100-200之间的偶数:

5.random.choice('abcdeapejad'),从所给的字符串中随机选择字符

6.random.sample('abcdoeuaja;a', 3),从所给的字符串中选取对应数量的字符

7.random.choice(['abc', 'apple', 'orange', 'banana'])随机选择字符串

8.随机排序 random.shuffle(list)

使用linux系统产生的随机字符串

1. xRand =string.atoi(os.popen('head -n 80 /dev/urandom | tr -dc 0-9 | head -c9').read(), 10),string.atoi(str,n)的作用是将str转化为十进制整数,n为str代表的进制数

2. xRand =string.atof(os.popen('head -n 80 /dev/urandom | tr -dc 0-9 | head -c9').read()),string.atof(str)的作用是将str转化为浮点数


使用随机模块求pi值

import os
import string
from random import random
count = 0
DARTS = 2**26
print(DARTS)
def distancdByXY(x,y):
    return (x**2 + y**2)**0.5
for i in range(0,DARTS):
    xRand, yRand = random(), random()
    #print("x,y: ", xRand, yRand)
    #print("distance: ", distancdByXY(xRand, yRand))
    if distancdByXY(xRand, yRand) <= 1.0:
        count = count+1
pi = 4*(float(count)/float(DARTS))
print(pi)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值