简体   繁体   中英

generating a log normal distribution using R

I would like to generate a log-normal distribution to use in my Python code to alter the rate in which I hit the server. Can anyone please guide me in generating the same?

Unless your heart is set on using R there is no need for external libraries. Python's builtin random module is well suited for general purpose use. It can generate random numbers from a variety of common distributions.

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

If you are using Rpy2 this should get you started:

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)

In R you can use rlnorm but why don't you use numpy and do it directly in Python.

Look at this document: http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM