使用R生成对数正态分布

-1 投票
2 回答
1646 浏览
提问于 2025-04-17 11:04

我想在我的Python代码中生成一个对数正态分布,用来改变我访问服务器的频率。有没有人能指导我怎么生成这个分布呢?

2 个回答

5

如果你不特别想用R语言的话,其实不需要额外的库。Python自带的random模块就很适合一般的使用。它可以从多种常见的分布中生成随机数。

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)
3

在R语言中,你可以使用 rlnorm 这个函数,但为什么不直接在Python中用numpy来实现呢?

可以看看这个文档: http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html

撰写回答