12.10Random numbers. 4tH 4tH Forth compiler
Διαφήμιση
Διαφήμιση
CHAPTER 12. STANDARD LIBRARIES
12.10
Random numbers
176
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. Just include the proper file: include lib/random.4th
And initialize it: randomize
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 subtract 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. If you don’t like to write this code yourself, you can always include choose.4th. After including that you can simply get a predetermined range of number by simply writing: include lib/choose.4th
6 choose 1+
Which is in fact your perfect dice simulation, because it returns a number between 1 and 6.
”CHOOSE” in itself provides a number between 0 and 5 in this example.
Sometimes you want the randomizer to provide a preset range of numbers. There is an variable called ”SEED” which determines what range of numbers is provided. ”RAN-
DOMIZE” initializes it with the setting of the internal clock, which is the same value that
’TIME’ returns. Yes, that means that if you call ”RANDOMIZE” twice within a second, the randomizer will return the same range of numbers. Presetting the randomizer is pretty trivial:
1234567890 seed !
Finally, under the hood it is not a single randomizer, but two! Default a modified
5
BSD algorithm is used, but you can also default to the standard Micrsoft algorithm by defining the appropriate pragma:
[pragma] MS-random include choose.4th
5
The standard BSD algorithm is notoriously flawed, especially the lower bytes of the returned random number.
Λήψη
Διαφήμιση