[英]generating a log normal distribution using R
我想生成一个对数正态分布,以在我的Python代码中使用以更改击中服务器的速率。 谁能指导我生成相同的东西?
除非您决心使用R,否则不需要外部库。 Python的内置随机模块非常适合一般用途。 它可以从各种常见分布中生成随机数。
import math
import random
#generate 10k lognormal samples with mean=0 and stddev=1
samples = [random.lognormvariate(0,1) for r in xrange(10000)]
#demonstrate the mean and stddev are close to the target
#compute the mean of the samples
log_samples = [math.log(sample) for sample in samples]
mu = sum(log_samples)/len(samples)
#compute the variance and standard deviation
variance = sum([(val-mu)**2 for val in log_samples])/(len(log_samples)-1)
stddev = var**0.5
print('Mean: %.4f' % mu)
print('StdDev: %.4f' % stddev)
#Plot a histogram if matplotlib is installed
try:
import pylab
hist = pylab.hist(samples,bins=100)
pylab.show()
except:
print('pylab is not available')
如果您使用的是Rpy2,则可以开始使用:
import rpy2.robjects as robjects
#reference the rlnorm R function
rlnorm = robjects.r.rlnorm
#generate the samples in R
samples = rlnorm(n=10000, meanlog=1, sdlog=1)
在R中,您可以使用rlnorm
但是为什么不使用numpy并直接在Python中进行呢?
查看此文档: http : //docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.