Search code examples
pythonrandomnormal-distributioninverse

Inverse normal random number generation in python?


I've used random.normal() in the past to generate a single number who, if called multiple times, in aggregate would create a bell curve distribution. What I'm trying to do now is to create the opposite / inverse, where the distribution is biased towards the extremes within a range? There are built in functions in excel that seem to do what I want. Is there a way to do it in python? Thank you


Solution

  • It appears you want a distribution with an "upside-down bell curve" compared to the normal distribution. If so, then the following method implements this distribution via rejection sampling and a modified version of the standard normal distribution. 'x0' and 'x1' are the ranges of numbers to generate.

    def invertedNormal(x0, x1):
      # Get the ends of the PDF (the bounding
      # box will cover the PDF at the given range)
      x0pdf = 1-math.exp(-(x0*x0))
      x1pdf = 1-math.exp(-(x1*x1))
      ymax = max(x0pdf, x1pdf)
      while True:
        # Choose a random x-coordinate
        x=random.random()*(x1-x0)+x0
        # Choose a random y-coordinate
        y=random.random()*ymax
        # Return x if y falls within PDF
        if y < 1-math.exp(-(x*x)):
          return x