Level 3, lesson 20

# 3.20 Random numbers

If you want to program a game or a simulation, you'll probably need random number generation. Of course, you can do that too with 4tH. It generates a number between 0 and 'MAX-RAND', but we'll teach you how to generate a number for virtually any range below that.

There are two things important when you want to do that: the range limit and the lower limit. Say, we want to simulate a dice with numbers in a range from 1 to 6. The lower limit is 1. We substract that from the upper limit to get the range limit.

So: upper limit minus lower limit gives a range limit of five (6 - 1 = 5). The general formula looks like this:

<range-limit> 1+ random * max-rand 1+ / <lower limit> +

When we apply this to the dice-example, the complete formula is:

         5 1+ random * max-rand 1+ / 1 +

This will give you a dice-simulation, that produces random numbers between 1 and 6. Happy? Then thank Wil Baden for the algorithm!