CP- Random Lesson

Random

The functions you have been creating have been void return types. Functions can also return information. Random is a special function that is used to generate a random number and return that value. Therefore it is referred to as a return function.  

random() is a function in Processing that produces random numbers and returns a value. There are two random() functions.  One requires one number as an argument and the other requires two arguments.

random(100); This returns a floating point number starting at 0 and up to but not including 100.    

If you supply two arguments in the parameter it specifies the beginning and ending range for the random number.  

random(1, 100); If two parameters are specified, the function will return a float with a value between the two values. For example, random(1,100)   returns values starting at 1 and up to (but not including) 100.    

You could use the random function in the fill method, stroke method, or coordinate for the primitive shapes.  For example:

fill(random(0,256), random(0,256), random(0,256));

Casting

If you want to produce a whole number rather than a float you must cast random to an int.  

Casting is used with numbers to convert integers to doubles or floating point numbers and doubles and floating point numbers to integers. You simply put the data type that you want to cast the variable to in parenthesis in front of the variable or in this case the function.  

int r =   (int)random(1,100);  The random number has been cast to an int. This will store a random integer between 1 and 100 in the variable r.

int r = (int)random(0,256);

int g = (int)random(0,256);

int b = (int)random(0,256);

fill(r, g, b);

[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION