Skip to content

Randomness#

So far, we always picked our own numbers for everything. This ends now. From here on out, we let the machine pick the numbers! Well, not always, but sometimes.

Computers usually do this by something we call a "Pseudorandom Number Generator", often abbreviated as PRNG. That's usually all we need and processing has a few nice ways to get a decently random number for the purposes of art or games.

Random often is not

Computers are pretty bad at real randomness. For places where randomness counts, we have specialised "cryptographically secure random number generators". As the name suggests, these are commonly used in cryptography.

Getting a random number#

float myFirstRandomNumber = random(1);
println(myFirstRandomNumber);

random(1) gives you a random number between 0 and 1. It is then stored in our newly declared variable myFirstRandomNumber. While you can't know the value beforehand, it could be . You can use that variable like any other variable. You can put it somewhere (we're just printing its value) but it could also go into places where we used numbers before.

Conveniently scaling a random number#

We rarely need a number between 0 and 1, but this is a form we can easily perform calculations on. Need a number between 0 and 1000? Just multiply your random number by 1000 and you're done! This case is so common, though, that Processing offers a more convenient way.

float secretPIN = random(1000);
println(secretPIN);

If we give a different parameter to random(), we can tell it to give us a random number from a greater range of numbers. In this case, we'll get a number between 0 and 1000 - mind you they are still float numbers, so your result could be .

Another common case is a lower boundary and an upper boundary at the same time. You may want to get a random number between 50 and 250 where you want to spawn a new enemy character. Processing's random() can also take two parameters like this:

float enemyPosition = random(50, 250);
println(enemyPosition);

That new position could be !

Relevant excerpt from Learning Processing#

(the section starts at 1:53:20 and runs through 2:02:46, the video should start and stop on these automatically.)