# Best random number generator

I have found that the random number function isn’t quite a normal distribution. My experiments result in errors over 10% at times, even with 100 samples. I am working on a coin toss program. Are there better formulations out there?

Thanks

The `random();` function is pseudo-random, which means it is not truly random (nothing can be), but it has results that appear random.

However, even with true randomness, there will always be errors. For example, using your 100 samples, if you’re doing `random(1,2);` there’s a 1/10000 chance of all the numbers being around the same.

1 Like

There are actually quite some ways to get „true“ randomness by using randomSeed() and adding an outside Variable like temperature or similar, But that might be too much. And i don‘t quite get what you mean with error, But if you mean that a number gets repeated twice in a row, then that can happen Even with the Most Perfect randomness.

Can you be more specific about what you’re trying to do? I’m confused by the fact that you’re looking for a normal distribution, but with coin tosses. Are you, for example, counting the number of heads that occur in 100 tosses? (This follows a binomial distribution, which does look approximately normal for such a large sample.) And, like @Lexyth, I’m not sure what you mean by an error. I think it would help a lot if you posted your code.

I guess what you are looking for is randomGaussian see reference.

1 Like

+1 for randomGaussian – it could also be called “randomNormal.”

Note this:

There is theoretically no minimum or maximum value that randomGaussian() might return. Rather, there is just a very low probability that values far from the mean will be returned; and a higher probability that numbers near the mean will be returned.

In practice this means that you often might need to use map() followed by constrain() to fit the gaussian to your desired random range.

``````float gaussianRange(float min, float max, float xdist) {
float rg = randomGaussian();
rg = map(rg, -xdist, xdist, min, max);
return constrain(rg, min, max);
}
``````

Here is how that looks in practice:

``````int[] bins;

void setup() {
size(200, 200);
fill(0, 32);
noStroke();
}

void draw() {
background(255);
bins = new int[width];
for (int i=0; i<8000; i++) {
int val = (int)gaussianRange(0, width-1, -3);
bins[val] = bins[val] + 1;
}
for (int i=0; i<bins.length-1; i++) {
ellipse(i, height - bins[i], 10, 10);
}
}

float gaussianRange(float min, float max, float xdist) {
float rg = randomGaussian();
rg = map(rg, -xdist, xdist, min, max);
return constrain(rg, min, max);
}
``````

Depending on your application, if you are generating random values in a given range then you may want to clamp outliers, or throw them away, or re-roll them.