numpy 随机数random/随机漫步介绍

很多网络演化编程中都会用到生成随机数,今天找了一下随机数说明手册,整理一下:

(1)random.seed([x])
伪随机数生成模块。如果不提供 seed,默认使用系统时间。使用相同的 seed,可以获得完全相同的随机数序列,常用于算法改进测试。
>>>from random import *
>>>a = Random(); a.seed(1)
>>>[a.randint(1, 100) for i in range(20)]
[14, 85, 77, 26, 50, 45, 66, 79, 10, 3, 84, 44, 77, 1, 45, 73, 23, 95, 91, 4]

>>>b = Random(); b.seed(1)
>>>[b.randint(1, 100) for i in range(20)]
[14, 85, 77, 26, 50, 45, 66, 79, 10, 3, 84, 44, 77, 1, 45, 73, 23, 95, 91, 4]

(2)random.random
用于生成一个0到1的随机符点数: 0 <= n < 1.0

(3)random.uniform
用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成的随机数n: a <= n <= b。如果 a  <b, 则 b <= n <= a。
   
(4)random.randint
用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b。size是表示生成总共多少个数。若size=2,则表示该数组里有2个元素。

(5)random.randrange
从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。

(6)random.choice
从序列中获取一个随机元素。参数sequence表示一个有序类型。这里要说明 一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。list, tuple, 字符串都属于sequence。

(7)random.shuffle
用于将一个列表中的元素打乱。

(8)random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。

这个模块很 "变态",还支持三角、β分布、指数分布、伽马分布、高斯分布等等非常专业的随机算法。

(9)random.triangular(low, high, mode)

Return a random floating point number N such that low <= N <= high and with the specified mode between those bounds. The low and highbounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.

(10)random.betavariate(alpha, beta)β分布
Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1.

(11)random.expovariate(lambd)指数分布

Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called “lambda”, but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative.

(12)random.gammavariate(alpha, beta)伽马分布

Gamma distribution. (Not the gamma function!) Conditions on the parameters are alpha > 0 and beta > 0.

(13)random.gauss(mu, sigma)高斯分布
Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function defined below.

(14)random.lognormvariate(mu, sigma)对数正态分布
Log normal distribution. If you take the natural logarithm of this distribution, you’ll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero.

(15)random.normalvariate(mu, sigma)正态分布

Normal distribution. mu is the mean, and sigma is the standard deviation.
random.vonmisesvariate(mu, kappa)
mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi.

(16)random.paretovariate(alpha)帕累托分布
Pareto distribution. alpha is the shape parameter.

(17)random.weibullvariate(alpha, beta)

Weibull distribution. alpha is the scale parameter and beta is the shape parameter.

随机生成数例子如下

samples=np.random.normal(size=(4,4)) #normal得到一个标准正态分布(4*4数组)
print samples
#python内置的random模块则只能一次生成一个样本值,但是numpy.random块不止一个数量级
from random import normalvariate
N=1000000
samples=[normalvariate(0,1) for _ in xrange(N)]  #normalvariate(mu,sigma)两个参数,第一个mu是均值,sigma是标准差
print samples

numpy.random函数

seed 		确定随机数生成器的种子
permutation		返回一个序列的随机排列或返回一个随机排列的范围
shuffle		对一个序列就地随机排列
rand 		产生均匀分布的样本值
randit		从给定的上下限范围内随机选取整数
randn		产生正态分布(平均值为0,标准差为1)的样本值
binomial	产生二项分布的样本值
normal		产生正态(高斯)分布的样本值
beta		产生Beta分布的样本值
chisquare	产生卡方分布的样本值
gamma		产生Gamma分布的样本值
uniform		产生在[0,1]中均匀分布的样本值

二.随机漫步的介绍

例1:假设醉汉每一步的距离是1或2,方向也完全随机,360度不确定,然后模拟醉汉的行走路径.
import numpy as np
from numpy import random
import matplotlib.pyplot as plt
from numpy.linalg import inv,qr

# 假设醉汉每一步的距离是1或2,方向也完全随机,360度不确定,然后模拟醉汉的行走路径.
N = 500 # steps

r = np.random.randint(1,3,N) # move 1 or 2 units of distance each step,N是步数,也就N个数
theta = np.radians(np.random.randint(0,361,N)) #一个是方向,是一个度数,0-360,

# np.cumsum Return the cumulative sum of the elements along a given axis.
#注意转化为弧度,每走一步,坐标值就是之前坐标值之和,用cumsum函数可以很方便地实现
x = np.cumsum(r*np.cos(theta)) #cumsum数组内的所有元素累加
y = np.cumsum(r*np.sin(theta))
plt.plot(x,y)
plt.show()
例2:用python里random来实现1000步的随机漫步
#用pytho里random来实现1000步的随机漫步
position=0
walk=[position]
steps=1000 #步长
for i in xrange(steps):
    step=1 if random.randint(0,1) else -1 #randint(0,1)是范围,if randint(0,1)步长就=1,否则就为-1
    position +=step #前面的位置+步长就是走出多远了,累加
    walk.append(position) #将新的位置赋给walk
投硬币,步长1000,两个数中任选 一个,将其分别设置为1或者-1,然后计算累计和
#投硬币,步长1000,两个数中任选 一个,将其分别设置为1或者-1,然后计算累计和
nsteps=1000 #步长
draws=np.random.randint(0,2,size=nsteps) #范围是(0,2)但是是不包括2,故只是0,1,size=nsteps是指元素的个数是1000个
print draws
steps=np.where(draws>0,1,-1) #draws>0则step=1,否则steps=-1
walk=steps.cumsum() #将steps累计求和
print walk.min() #可取walk的最小值
print walk.max() #可取walk的最大值
#假设我们想要知道本次随机漫步需要多久才能距离初始0点至少10步元(任一方向均可)。np.abs(walk)>=10可以得到一个布尔型数组,
#它表示的是距离是否达到或超过10,而我们想要知道的是第一个10或者-10的索引。可以用argmax来解决
#argmax它返回的是该布尔型数组第一个最大值的索引(True就是最大值)
#注意:下面使用argmax并不是很高效,它无论如何都会对熖组进行完全扫描。本例中只要发现一个True,我们就知道它是个最大值了
print (np.abs(walk)>=10).argmax()
一次模拟多个随机漫步
例3:希望模拟多个随机漫步过程(比如5000个),只要给numpy.random函数传入一个二元元组就可以产生一个二维数组,
然后我们就可以一次性计算5000个随机漫步过程(一行一个)的累计和了。
nwalks=5000
nsteps=1000
draws=np.random.randint(0,2,size=(nwalks,nsteps)) #size(nwalks,nsteps)生成5000行1000列的数组。数组里的元素是0,1
# print draws
steps=np.where(draws>0,1,-1) #draws>0,steps=1,否则step=-1
walks=steps.cumsum(1) #cumsum累加,cumsum(1)每一行累加,若是cumsum(0)是每一列累加
print walks #累加之后的walk数组
print walks.max()
print walks.min()

#我们来计算30和-30的最小穿越时间。因为不是5000个过程都达到了30,我们可以用any方法来对此进行检查
hits30=(np.abs(walks)>=30).any(1) #行
print hits30
#np.abs得到的结果是布尔型如下:
# [ True False  True ..., False  True False]
print hits30.sum() #到达30或-30的数量,因为hits30的值是布尔型,True为1,False为0 ,故计算为True的值就是统计数量
#然后我们利用这个布尔型数组选出那些穿越了30(绝对值)的随机漫步(行),并调用argmax在轴1上获取穿越时间
crossing_time=(np.abs(walks[hits30])>=30).argmax(1) #行
print crossing_time

#可尝试其它分布方式得到漫步数据
#如normal用于生成指定均值和标准差的正态分布数据
steps=np.random.normal(loc=0,scale=0.25,size=(nwalks,nsteps))




猜你喜欢

转载自blog.csdn.net/u012474716/article/details/80256530