News:

Printed Amstrad Addict magazine announced, check it out here!

Main Menu
avatar_EgoTrip

Random Number Generator in Machine Code

Started by EgoTrip, 09:39, 16 December 10

Previous topic - Next topic

0 Members and 2 Guests are viewing this topic.

g0blinish


andycadley

Quote from: Nich on 12:16, 23 December 10
Even RANDOMIZE TIME sometimes isn't good enough. Try this code to see what I mean:

10 MODE 2
20 FOR a=1 TO 23
30 RANDOMIZE TIME
40 FOR b=1 TO 25
50 PRINT USING("## ");INT(RND*100);
60 NEXT b
70 PRINT
80 NEXT a


After you obtain about five or six numbers, the numbers are no longer random! However, if you re-initialise the random number seed by using RANDOMIZE TIME:RANDOMIZE RND, the quality of the random numbers is much better. (This was something I learnt from a listing in Computing with the Amstrad. ;))

Embarrasing late to the party, but I'm actually surprised nobody commented on this previously. You aren't supposed to call RANDOMIZE repeatedly, because every time you do it resets the seed so you'll end up using the same small subset of the PRNG.

The "correct" way to do the above in BASIC would be more like:

10 MODE 2
20 RANDOMIZE TIME
30 FOR a=1 TO 23
40 FOR b=1 TO 25
50 PRINT USING("## ");INT(RND*100);
60 NEXT b
70 PRINT
80 NEXT a


which moves the seed generation outside of the loop and thus generates a much more random sequence.

Perhaps someone more wiki-knowledgable could correct the entry?

Nich

Quote from: andycadley on 21:40, 20 November 14
Embarrasing late to the party, but I'm actually surprised nobody commented on this previously. You aren't supposed to call RANDOMIZE repeatedly, because every time you do it resets the seed so you'll end up using the same small subset of the PRNG.

The "correct" way to do the above in BASIC would be more like:

10 MODE 2
20 RANDOMIZE TIME
30 FOR a=1 TO 23
40 FOR b=1 TO 25
50 PRINT USING("## ");INT(RND*100);
60 NEXT b
70 PRINT
80 NEXT a


which moves the seed generation outside of the loop and thus generates a much more random sequence.

Perhaps someone more wiki-knowledgable could correct the entry?
I think you haven't fully understood what I was trying to convey with my example program.

Most programs that use RANDOMIZE TIME will only use it once, as is the case in the BASIC program you've posted. However, try running that program, resetting it, then running it again, resetting it again, running it a third time, resetting it again... After about six or seven numbers, the same sequence of numbers is generated (93, 54, 6, 98, 14, 3, 18, 35...)! Hence there is a need to use RANDOMIZE TIME:RANDOMIZE RND to reinitialise the seed and prevent the same sequence of 'random' numbers being generated every time you run a program.

The attached screenshots demonstrate the problem more clearly.

[attach=2] [attach=3] [attach=4] [attach=5]

Powered by SMFPacks Menu Editor Mod