笔记-python-standard library-9.6 random

1.      random

source code:Lib/random.py

1.1.    functions for integers

random.randrange(stop)

random.randrange(start, stop[, step])

从range(start, stop, step)中返回一个随机选择的元素。注意并不会生成一个range对象。

random.randint(a,b)

return a random integer N such that a<=N <=b.alias for randrange(a, b+1)

1.2.    functions for sequences

random.choice(seq)

return a random element from the non-empty sequence seq. if seq is empty, raises IndexError.

random.shuffle(x[, random])   shuffle the sequence x in place.

the optional argument random is a 0-argument function returning a random float in[0.0,1.0];by default, this is the function random().

random.sample(population,k)

return a k length list of unique elements chosen from the population sequence or set.

注意,已选择过的元素不会再次选中。

1.3.    real-valued distriutions

random.random()

return the next random floating point number in the range [0.0,1.0].

random.uniform(a, b)

return a random floating point number N such that a<=N<=b for a<=b and b<=N<=a for b<a.

1.4.    examples

下面是一些例子,基本可以满足常用场景。

Basic examples:

>>> random()                             # Random float:  0.0 <= x < 1.0
0.37444887175646646
 
>>> uniform(2.5, 10.0)                   # Random float:  2.5 <= x < 10.0
3.1800146073117523
 
>>> expovariate(1 / 5)                   # Interval between arrivals averaging 5 seconds
5.148957571865031
 
>>> randrange(10)                        # Integer from 0 to 9 inclusive
7
 
>>> randrange(0, 101, 2)                 # Even integer from 0 to 100 inclusive
26
 
>>> choice(['win', 'lose', 'draw'])      # Single random element from a sequence
'draw'
 
>>> deck = 'ace two three four'.split()
>>> shuffle(deck)                        # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']
 
>>> sample([10, 20, 30, 40, 50], k=4)    # Four samples without replacement
[40, 10, 50, 30]

Simulations:

>>> # Six roulette wheel spins (weighted sampling with replacement)
>>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)
['red', 'green', 'black', 'black', 'red', 'black']
 
>>> # Deal 20 cards without replacement from a deck of 52 playing cards
>>> # and determine the proportion of cards with a ten-value
>>> # (a ten, jack, queen, or king).
>>> deck = collections.Counter(tens=16, low_cards=36)
>>> seen = sample(list(deck.elements()), k=20)
>>> seen.count('tens') / 20
0.15
 
>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> trial = lambda: choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5
>>> sum(trial() for i in range(10000)) / 10000
0.4169
 
>>> # Probability of the median of 5 samples being in middle two quartiles
>>> trial = lambda : 2500 <= sorted(choices(range(10000), k=5))[2]  < 7500
>>> sum(trial() for i in range(10000)) / 10000
0.7958

Example of statistical bootstrapping using resampling with replacement to estimate a confidence interval for the mean of a sample of size five:

# http://statistics.about.com/od/Applications/a/Example-Of-Bootstrapping.htm
from statistics import mean
from random import choices
 
data = 1, 2, 4, 4, 10
means = sorted(mean(choices(data, k=5)) for i in range(20))
print(f'The sample mean of {mean(data):.1f} has a 90% confidence '
      f'interval from {means[1]:.1f} to {means[-2]:.1f}')

Example of a resampling permutation test to determine the statistical significance or p-value of an observed difference between the effects of a drug versus a placebo:

# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import mean
from random import shuffle
 
drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean(drug) - mean(placebo)
 
n = 10000
count = 0
combined = drug + placebo
for i in range(n):
    shuffle(combined)
    new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):])
    count += (new_diff >= observed_diff)
 
print(f'{n} label reshufflings produced only {count} instances with a difference')
print(f'at least as extreme as the observed difference of {observed_diff:.1f}.')
print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null')
print(f'hypothesis that there is no difference between the drug and the placebo.')

Simulation of arrival times and service deliveries in a single server queue:

from random import expovariate, gauss
from statistics import mean, median, stdev
 
average_arrival_interval = 5.6
average_service_time = 5.0
stdev_service_time = 0.5
 
num_waiting = 0
arrivals = []
starts = []
arrival = service_end = 0.0
for i in range(20000):
    if arrival <= service_end:
        num_waiting += 1
        arrival += expovariate(1.0 / average_arrival_interval)
        arrivals.append(arrival)
    else:
        num_waiting -= 1
        service_start = service_end if num_waiting else arrival
        service_time = gauss(average_service_time, stdev_service_time)
        service_end = service_start + service_time
        starts.append(service_start)
 
waits = [start - arrival for arrival, start in zip(arrivals, starts)]
print(f'Mean wait: {mean(waits):.1f}.  Stdev wait: {stdev(waits):.1f}.')
print(f'Median wait: {median(waits):.1f}.  Max wait: {max(waits):.1f}.')

笔记-python-standard library-9.6 random的更多相关文章

  1. Python Standard Library

    Python Standard Library "We'd like to pretend that 'Fredrik' is a role, but even hundreds of vo ...

  2. The Python Standard Library

    The Python Standard Library¶ While The Python Language Reference describes the exact syntax and sema ...

  3. Python语言中对于json数据的编解码——Usage of json a Python standard library

    一.概述 1.1 关于JSON数据格式 JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 46 ...

  4. 《The Python Standard Library》——http模块阅读笔记1

    官方文档:https://docs.python.org/3.5/library/http.html 偷个懒,截图如下: 即,http客户端编程一般用urllib.request库(主要用于“在这复杂 ...

  5. 《The Python Standard Library》——http模块阅读笔记2

    http.server是用来构建HTTP服务器(web服务器)的模块,定义了许多相关的类. 创建及运行服务器的代码一般为: def run(server_class=HTTPServer, handl ...

  6. 《The Python Standard Library》——http模块阅读笔记3

    http.cookies — HTTP state management http.cookies模块定义了一系列类来抽象cookies这个概念,一个HTTP状态管理机制.该模块支持string-on ...

  7. Python Standard Library 学习(一) -- Built-in Functions 内建函数

    内建函数列表 Built-in Functions abs() divmod() input() open() staticmethod() all() enumerate() int() ord() ...

  8. [译]The Python Tutorial#10. Brief Tour of the Standard Library

    [译]The Python Tutorial#Brief Tour of the Standard Library 10.1 Operating System Interface os模块为与操作系统 ...

  9. C++11新特性——The C++ standard library, 2nd Edition 笔记(一)

    前言 这是我阅读<The C++ standard library, 2nd Edition>所做读书笔记的第一篇.这个系列基本上会以一章一篇的节奏来写,少数以C++03为主的章节会和其它 ...

  10. [译]The Python Tutorial#11. Brief Tour of the Standard Library — Part II

    [译]The Python Tutorial#Brief Tour of the Standard Library - Part II 第二部分介绍更多满足专业编程需求的高级模块,这些模块在小型脚本中 ...

随机推荐

  1. CentOS6.5 环境安装配置

    一.GO环境配置 1.运行命令进入/usr/local/src目录:cd /usr/local/src 2.下载安装包:运行wget --no-check-certificate https://st ...

  2. redis在Windows下以后台服务一键搭建集群(单机--伪集群)

    redis在Windows下以后台服务一键搭建集群(单机--伪集群) 一.概述 此教程介绍如何在windows系统中同一台机器上布置redis伪集群,同时要以后台服务的模式运行.布置以脚本的形式,一键 ...

  3. Mysql数据库学习总结(一)

    数据库概念 数据库(Database)是按照数据结构来组织.存储和管理数据,建立在计算机存储设备上的仓库. 简单说,数据库就是存放数据的仓库.和图书馆存放书籍.粮仓存放粮食类似. 数据库分类 分为 关 ...

  4. 绿卡基础知识:I-129

    绿卡基础知识:I-129 标签: 绿卡基础知识 I-129 表格本不该你来填的.那是你老板的 business.在美国工作,除非是公民或有绿卡,都需要移民局的批准.如果你没有 EAD,I-129 就是 ...

  5. 打造颠覆你想象中的高性能,轻量级的webform框架-----如何替换webform的垃圾控件(第一天)

    前文描述: 随着.net  推出 MVC框架以来,webform 与 mvc 的争论一直没有停止过,一直以来 mvc 的 拥护者远远高于 webform,但是webfrom的有些优势又是mvc而无法替 ...

  6. IOS 截屏(保存到相册中)

    @interface NJViewController () /** * 点击截屏按钮 */ - (IBAction)captureView:(UIButton *)sender; /** * 白色v ...

  7. C/C++语言补缺 宏- extern "C"-C/C++互调

    1. 宏中的# 宏中的#的功能是将其后面的宏参数进行字符串化操作(Stringizing operator),简单说就是在它引用的宏变量的左右各加上一个双引号. 如定义好#define STRING( ...

  8. Mybatis-动态 SQL语句

    if标签 判断语句,用户单条件分支判断 where标签 为了简化上面where 1=1的条件拼装,我们可以采用标签来简化开发 同 foreach标签 场景:传入多个 id 查询用户信息 标签用于遍历集 ...

  9. python实现二叉树的镜像

    题目描述 操作给定的二叉树,将其变换为源二叉树的镜像. 输入描述: 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ ...

  10. Java Web Application使Session永不失效(利用cookie隐藏登录)

    在做 Web Application 时,因为 Web Project 有 session 自动失效的问题,所以如何让用户登录一次系统就能长时间运行三个月,就是个问题. 后来,看到 session 失 ...