Random weighted number between two numbers?

Here’s my problem.

I have two numbers: 1.1501344 & 1.1816746. I’d like to generate a random number between these two numbers, but weighted to the ‘center’ of the number: 1.1659045. So there is a higher chance of the random number being closer to the 1.16 value, rather than the 1.15 & 1.18 values.

I’ve tried using random.nextGaussian() but that creates values < -1 and > +1.

Any ideas?

The easiest the triangle distribution (https://en.wikipedia.org/wiki/Triangular_distribution), but it depends on how you what distribution curve to look.

Of course wikipedia is about as clear as ever:



// symmetric triangle distribution: result on (-1,1)
public static float symmetricTriangular()
{
   return nextFloat()-nextFloat());  // from random number generator of choice
}

// symmetric triangle distribution: result on [lo, hi)
public static float symmetricTriangular(float lo, float hi)
{
    float halfDiff = 0.5f*(hi-lo);
    float triDist  = nextFloat()+nextFloat();   // triangle on [0,2)
    return halfDiff*triDist + lo;
}

You could still use a Gaussian distribution, or any distribution generating values within [A, B], and do a simple linear interval mapping to [a, b] (i.e. “stretching the interval”) via:


double val = Random.nextGaussian();
double a = 1.1501344; // the min value of our target interval
double b = 1.1816746; // the max value of our target interval
double value = (val + 1.0) * (b - a) / 2.0 + a; // <- interval mapping from [-1, +1] -> [a, b]
// value is the gaussian distribution within [a, b]

Thanks for those, I’ll give them both a go.

Quick question, where did you get the ‘val’ value from? Would that be the ‘center’ value of 1.165 I mentioned above?

Sorry, modified the post. It is of course the value you want to map. I just copied the interval mapping code from some SF answer.

Note that the Gaussian distribution isn’t bounded…not sure if that’s what you want.