The Coder's Handbook

Random and Casting

RANDOM NUMBERS

Making Random Numbers

Your program can generate a random number in a specified range.


void random(float max)

  • Returns a random float between 0 and max


float xPos = random(width); // Sets xPos to a random number from 0 to width


void random(float min, float max )

  • Returns a random float between min and max


float xPos = random(200, 500); // Sets xPos to a random number from 200 to 500



It's important to note that random generates a value that includes minimum but excludes maximum. For example, random(50, 200) actually generates a number between 50 and 199.999999999. This will be important later!

In the physical world, we use tools like dice to try and approximate random numbers. But they're not truly random - they're based on physics. As a result, they only produce pseudorandom numbers. They're "random enough" for our purposes.


Computers aren't that much better! We use the system clock and math to make pseudorandom numbers. But it's actually very difficult to find true randomness in nature.

An Example


Let's look at some example code in action. Copy the code below into a new processing project. Run the program to see it in action. Try changing some values and see what happens! How might you get different colors to appear?


float redAmount;

float xPos;

float yPos;


void setup()

{

fullScreen();

}


void draw()

{

xPos = random(50, width - 50);

yPos = random(400, height - 400);

redAmount = random(255);


fill(redAmount, 0, 0);

ellipse(xPos, yPos, 50, 50);

}

CASTING

Types and Casting


Remember that every variable comes in a type. So far, we've studied three:

  • boolean - True or False

  • int - Integer values

  • float - Decimal values


You can use casting to convert from one type to another. For example, you might use random and get a float, but want to make it into an int. Let's consider this situation in more detail:

Casting to an Int


Imagine you're designing a board game in processing, and want to simulate a die roll. You don't want to have a player roll "3.467" - only the values 1, 2, 3, 4, 5, or 6. We using casting to convert a float to an integer.


int dieRoll = (int) random(6) + 1; // dieRoll is exactly 1, 2, 3, 4, 5, or 6


Two things to consider about this code:

  • When casting to an integer, it always truncates the value. This means it always rounds down. For example, both 5.2 and 5.9 become 5.

  • Since random(6) only generates numbers up to 5.999999, we'd get a range of 0 to 5. If we wanted that to get 1 to 6, we add one to the expression.

RESOURCES

  • Chapter 4.6 - Random