3 Replies Latest reply on Oct 23, 2006 6:05 AM by 807598

# how to get a random gaussian float?

i want something that generates a random float from a Gaussian distribution.
java.util.random only gives me a double.

this class here says it can do it, but i cant find the code...
http://laseeb.isr.ist.utl.pt/sw/JDEAL/api/pt/laseeb/util/RNG.html

any help would be great thanks!
• ###### 1. Re: how to get a random gaussian float?
The code is available from http://laseeb.isr.ist.utl.pt/sw/JDEAL/
This links to a .zip file containing the source.

This is from the source of pt.laseeb.util.RNG
``````public class RNG extends Random
{
private static java.util.Random random;
private static long randomSeed;

static
{
randomSeed=System.currentTimeMillis();
random=new java.util.Random(randomSeed);
}

// other stuff

/**
* Generates a random float from a Gaussian distribution with the specified
* deviation.
* <p>
* @param dev the desired deviation.
* @return a random float from a Gaussian distribution with deviation
* <code>dev</code>.
*/
public static float gaussianFloat(float dev)
{
return (float)random.nextGaussian()*dev;
}

// other stuff
}``````
So it looks like using Random and casting the double to a float is as
good as it gets.

 Where does this [nobr] business come from?
• ###### 2. Re: how to get a random gaussian float?
ok. does anyone know how to scale these numbers so that they span the entire range of float values?

ie so that the max value is the max float value and the min value is the min float value.

thanks....
• ###### 3. Re: how to get a random gaussian float?
In general if you have a number x in the range (a,b) and you apply a
linear scaling x |-> c+(x-a)*(d-c)/(b-a) you'll end up with a number in
the range (c,d). If a number of x-values with a given distribution are
transformed in this way the resulting distribution will have a similar
"shape".

Care will be needed in implementing this because of the value of
(d-c) when you are scaling up to the full float range.

So for instance if the x-values were originally uniformly distributed the
transformed values will be as well. Likewise if the original values are
(rather roughly) gaussian, the transformed values will be as well. I
say "rather roughly" because values obtained from Random's
nextGaussian() will, in general, occupy the entire range of double.

If you cast the result of nextGaussian() you don't have to scale the
result. In fact the problem (if there is one) is the reverse: some of the
floats obtained this way will be infinite. This problem won't occur in
practice unless the mean and/or sd of your gaussian distribution is
very, very, very big.