View Full Version : Generate a random number between 0 and X
The Master
- 14th September 2010, 19:01
Hi, I already know i can use the RANDOM command to generate a 16 bit random number. The problem is that i dont know how to generate one that is between 0 and anything upto 255. The upper value is specified by another variable. Ive seen a few examples including one from this site that uses ** but i cant seem to get any of them to work correctly.
Im working mainly in assembly but i dont mind examples in PBP.
aratti
- 14th September 2010, 20:00
Hi, I already know i can use the RANDOM command to generate a 16 bit random number. The problem is that i dont know how to generate one that is between 0 and anything upto 255.
You can use only the low byte or the high byte of the randomized word.
Al.
The Master
- 14th September 2010, 20:24
Yes, Im using the low byte. That gives me 0-255 though. I have another variable that contains a value between 0 and 255 and i need the random number to be between 0 and that.
aratti
- 14th September 2010, 21:56
Something like this should work:
Rnd0 var word
Rnd1 var byte
Lim var byte ' your limiting variable (0 - 255)
Random Rnd0
Rnd1 = Rnd0 */ lim
Al.
The Master
- 14th September 2010, 22:23
Ive not seen that operator before. What does it do? Ive had a look at the online manual and it says it "returns the middle 16 bits of the 32-bit result". Im not sure if thats what i want.
I know i could get to the correct value using the following equation
Rnd1 = (Rnd0.byte0 / 255) * lim
That one wont work though because it will be rounded to 0 or 1 when dividing.
aratti
- 15th September 2010, 00:15
I know i could get to the correct value using the following equation
Rnd1 = (Rnd0.byte0 / 255) * lim
That one wont work though because it will be rounded to 0 or 1 when dividing.
Tray to multiply first.
Rnd1 = (Rnd0.byte0 * lim)/ 255 [which is the same as Rnd1 = (Rnd0 */ lim)]
Al.
The Master
- 15th September 2010, 01:27
Ahh, I think i understand how */ is working now. Ive tried both ways and they seem to be working for a few seconds then my LED freezes but i think thats to do with something else. Thanks for your help
The Master
- 15th September 2010, 10:52
Ive figured why the LED freezes now. After generating the random number i was using */ and storing the result back in the same variable. It looks like the RANDOM command uses whats already in the variable as a seed and as i was modifying the value to really low numbers, eventually it was hitting 0 and staying there. I added a second variable and its all working now
Powered by vBulletin® Version 4.1.7 Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.