使用R生成对数正态分布

时间:2012-01-25 17:51:23

标签: python r

我想生成一个日志正态分布,以便在我的python代码中使用它,这将改变我点击服务器的速率。任何人都可以指导我生成相同的。

2 个答案:

答案 0 :(得分:5)

除非你的心已经开始使用R,否则不需要外部库。 Python的内置random module非常适合一般用途。它可以从各种常见分布中生成随机数。

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)

答案 1 :(得分:3)

在R中,您可以使用rlnorm,但为什么不使用numpy直接在Python中执行。

请查看此文档:http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html