1

How to generate 10 random numbers from normal distribution using latin hypercube sampling technique in python 2.7? The range of the random number should be 5 to 14.

I tried following

import random
from random import randint
iter = 10
segSize = 1 / iter
for i in range(iter):
segMin = i * segSize
point = segMin+ (random.normalvariate(7.5,1)*segSize)
pointValue = (point * (14 - 5)) + 4
print point
print pointValue

Thanks

mrn
  • 425
  • 2
  • 15
  • 33

2 Answers2

1

Try this:

def rand:
 import random
 from random import randint
 iter = 10
 segSize = 1/float(iter)
 for i in range(iter):
         segMin = float(i) * segSize
         point = segMin + (random.normalvariate(7.5,1) * segSize)
         pointValue = (point * (14 - 5)) + 4
         print point
         print pointValue

Your issue seems to have been integer multiplication etc, which Python truncates to zero in your division.

When I run it, I get:

0.686848045493
10.1816324094
0.871425699273
11.8428312935
1.08794202088
13.7914781879
1.08502172623
13.7651955361
1.24462345735
15.2016111161
1.10687801576
13.9619021418
1.1394488663
14.2550397967
1.37407532844
16.3666779559
1.54666717385
17.9200045647
1.6465869841
18.8192828569
learner
  • 1,895
  • 2
  • 19
  • 21
  • Thank you so much. It worked. Just a query, how do I keep the number between 5 to 14? – mrn Oct 14 '12 at 18:14
  • 1
    That depends. Are you constrained to the normal distribution? [Here](http://stackoverflow.com/questions/6088077/how-to-get-a-random-number-between-a-float-range-python) [are](http://effbot.org/pyfaq/how-do-i-generate-random-numbers-in-python.htm) [some](http://effbot.org/librarybook/random.htm) [links](http://docs.python.org/library/random.html) if not. If so, what are you doing? The normal distribution isn't a set range, it's a measure of tendency. Describe more what you're doing if you have to use the normal distribution. – learner Oct 14 '12 at 18:24
0

Latin Hypercube Sampling (LHS) is supported by the SciPy 1.8.0 (see this link).

To generate a truncated normal sample using LHS:

from scipy.stats import qmc, norm, truncnorm
# Truncated normal sample using Latin Hypercube Sampling
mean, std = 10, 2
dimension, sample_num = 3, 10
clip_a, clip_b = 5, 14
a, b = (clip_a - mean) / std, (clip_b - mean) / std
sample = truncnorm(a, b, loc=mean, scale=std).ppf(lhd)

To generate a normal sample using LHS:

# normal sample using Latin Hypercube Sampling
lhd = qmc.LatinHypercube(d=dimension, optimization="random-cd").random(n=sample_num)
sample = norm(loc=mean, scale=std).ppf(lhd)

Alternatively, you can use pyDOE to generate LHS sample (see this link).

from pyDOE import lhs
lhd = lhs(dimension, samples=sample_num, criterion="m")
sample = norm(loc=mean, scale=std).ppf(lhd)
Penghui Guo
  • 101
  • 4