Non-Uniform Random Number Distribution Using Probabilities
There are many different ways we can produce a non-uniform distributions of random numbers. One simple way would be to fill an array with the appropriate distribution of possibilities, picking one random element from that array each time. Try:
int[] stuff = new int[5];
stuff[0] = 1;
stuff[1] = 1;
stuff[2] = 2;
stuff[3] = 3;
stuff[4] = 3;
int index = int(random(stuff.length));
println(stuff[index]);
This is a terribly inefficient example in many ways, but it’s easy to see how we now have a 40% chance of picking 1, 20% chance of picking 2, and 40% chance of picking 3. Think about how you might extend this code to work with a much larger array with many different possibilities. You might even consider using a java ArrayList, which would allow you to remove elements as you pick them if that were a requirement of your program.
Another strategy for how we can create a likelihood for different events to occur is to ask for a random number (for simplicity, we consider random numbers between 0 and 1) and only allow the event to happen if the random number we pick is within a certain range, i.e.
float prob = 0.10f; //to store a probability of 10%
float r = random(1); //get a random floating point value between 0 and 1
if (r < prob) { //if our random is less than .1
/*INSTIGATE THE EVENT HERE*/
}
In our applets, we are often tempted to simply map some parameter or variable to a random number (i.e. produce random colors, set random velocities, locations, etc.) producing a uniform distribution of values. However, a more interesting way is to assert control over the probabilities of a set of possible outcomes.
Outcome A — 10% | Outcome B — 60% | Outcome C — 30%
To implement this in code, we pick one random float and check where it falls (between 0 and 0.10 (10%) –> outcome A, between 0.10 and 0.70 (60%) –> B,
and between 0.70 and 1.0 (30%) –> C).
//probabilities for 3 different cases (these need to add up to 100% since something always occurs here!)
float red_prob = 0.10; // 10% chance of red color occurring
float green_prob = 0.60 + red_prob; // 60% chance of green color occuring
float blue_prob = 0.30 + green_prob; // 30% chance of blue color occuring
float num = random(1); // pick a random number between 0 and 1
if (num < red_prob) {
fill(255,0,0,50);
} else if (num < green_prob) {
fill(0,255,0,50);
} else {
fill(0,0,255,50);
}
ellipse(random(width),random(height),16,16);