0

I want a random number generator that almost never produces numbers that are near a given upper boundary. The odds should drop linearly to 0 to the upper boundary.

This is possibly best suited as a math-only question, but I need it in code form (pseudo-code is fine, more specifically any C-based language) for my use, so I'm putting it here.

Hamster
  • 2,962
  • 7
  • 27
  • 38
  • 1
    If you use `R`, you can draw a sample from, say, a lognormal distribution with `rlnorm(n, meanlog = 0, sdlog = 1)`. – ako Jul 12 '14 at 15:30
  • 1
    Exponentials and lognormals don't have a linear drop-off. – pjs Jul 12 '14 at 16:24

1 Answers1

2

If you want a linear drop-off what you're describing is called a triangle (or triangular) distribution. Given U, a source of uniformly distributed random numbers on the range [0,1), you can generate a triangle on the range [a,b) with its mode at a using:

def triangle(a,b)
    return a + (b-a)*(1 - sqrt(U))
end

This can be derived by writing the equation of a triangle for the specified range, scaling it so it has area 1 to make it a valid density, integrating to get the CDF, and using inversion.

As an interesting aside, this will still work if a >= b. For equality, you always get a (which makes sense if the range is zero). Otherwise, you get a triangle which goes from b to a and has its mode at a.

pjs
  • 18,696
  • 4
  • 27
  • 56