Click 'Run' to go.

*Let's think about making a random number between 2 and 7.*

First, let's consider the section of the ** number line** over which we want to get our random number. Here it is colored

Now, our random number will be at ** least** equal to

Notice that this ** distance** is equal to

Perhaps our random percent will be ** 37.5%**. Well,

Maybe our random percent will be ** 75%**. Now,

Where do we get the ** random percent** needed for this calculation? It turns out that this

*So, we have these:*

- The
value:*minimum**2* - The
value:*maximum**7* - The
between the minimum and maximum values:*distance**5 = 7 - 2* - A
:*random percent*,*random number function***rnd()**

** We will combine the above into and equation.** The variable

**x = 2 + rnd() * (7 - 2)**

** Let's generalize.** We want a random number between

**x = min + rnd() * (max - min)**

The above calculation is printed by the following demo.

Slow
Medium
Fast

Click 'Run' to go.

Click 'Run' to go.

The above method will never calculate a random number equal to the in the above example. That is because the value output by the random number function will never get to 7. It goes up to, but not including, 1.
1
So, let's calculate with a number close to , or 0.9999. That 99.99% times percent plus 5 is 2, not quite 6.9995.
7 |

*The flowchart for this demo looks like this:*

*In an imaginary computer language this could look like the following:*

min = -10; max = 10; print min + rnd() * (max - min);

*Suggested next article:*