Lesson 2.5

random(): A useful function

Watch The random() Function

Video for 2.5

Why use random()?

random() , when called again and again, gives you a way to change things with each call.

Example 2.5.1: How could you model the appearance of stars at night?

We can first create the “stars”.

We create a background just once in setup() – mostly black but with a hint of blue.

We draw many stars randomly on the screen. A size of 2 makes them look like stars in the night sky

  1. We can add a color object and use it to vary the colors – less appropriate for stars but more so for other type of objects.
  2. In this case we will use it to vary the “brightness” by varying the transparency.
  3. If we changed the color mode we could do this more directly.

Example 2.5.1

Example 2.5.2: How could you model a piece of pollen randomly being moved about ? For example, by collisions with air molecules.

Example 2.5.2

Exercise 2.5a: Use mousepressed() to place a set of circles randomly on the page. Provide a label to show in which order they were created.

Here are images after 5 and after 20 clicks.

Exercise 2.5a

Exercise 2.5b: Create a random set of points inside a square centered in the canvas.

Here are images after a few seconds and then later.

Exercise 2.5b

Exercise 2.5c: Create a random set of points (inside a circle) centered in the canvas. This could be the start of a model of a 1s orbital for a hydrogen atom, with the proton in the center (not shown).

Here are images after a few seconds, later, and later yet.

Exercise 2.5c

Exercise 2.5d: Create the following. The color scheme is optional.

Exercise 2.5d