Random numbers

Started by
11 comments, last by mrtie_dye 20 years, 10 months ago
Besides the srand( time(NULL) ) statement that you need to randomize the rand() function (that''s how I think of it although I''m sure it''s not the correct terminology), the statement

int num = ((rand() % 5) + 1) +((rand() % 5) + 1) +((rand() % 5) + 1) + 3; 


is incorrect. To simulate 3 die being rolled change it a tiny bit:

int num = ((rand() % 6) + 1) +((rand() % 6) + 1) +((rand() % 6) + 1); 


and you don''t want to do:

int num = (rand() % 16) + 3; 


for the reasons previously stated. It will not simulate 3 die, although it will give a number between 3-18.
Advertisement
quote:Original post by Edward Ropple
Define better.
Ok ready...

You'll get a better/more even distribution of random numbers with MAX_RAND.

Lets say my random number generater generates number generator generates numbers between 0-7..., and I want a random number between 0 - 5(d6), so

0 mod 6 = 0
1 mod 6 = 1
2 mod 6 = 2
3 mod 6 = 3
4 mod 6 = 4
5 mod 6 = 5
6 mod 6 = 0
7 mod 6 = 1

I have a bias towards 0 and 1.

0/7 * 5 = 0 (0)
1/7 * 5 = 0.71(1)
2/7 * 5 = 1.42(1)
3/7 * 5 = 2.14(2)
4/7 * 5 = 2.86(3)
5/7 * 5 = 3.58(4)
6/7 * 5 = 4.29(4)
7/7 * 5 = 5.0 (5)

Here I have a bias towards 1 or 4.

Having a bias towards 1 or 4 is slightly better than a bias of 0 or 1. Mod usually will be bias towards the lower values, while MAX_VALUE will usually be more bias towards the center.

So lets say our hero has to get a 4 or 5, or he dies...(typical D&D game) so there is 1/3 chance in total random die.(0-5 = 6)

2/6 = 0.33333333

for mod -> 2/8 = 0.25
for MAX_VALE 3/8 = 0.375

MAX_VALUE better aproximates the correct dice roll, giving a slight bias towards winning, which is also a good thing(tm) in RPGS

(edit - Confusing, fixed it up)

[edited by - dede on May 27, 2003 7:57:19 PM]
~~~~~Screaming Statue Software. | OpenGL FontLibWhy does Data talk to the computer? Surely he's Wi-Fi enabled... - phaseburn
quote:
Why cant you do something like (rand() % 11) ???

rand()%11 will give you a rand num between 0 and 10. not 1 and 10.


doh, nuts. Mmmm... donuts
My website

This topic is closed to new replies.

Advertisement