Click to See Complete Forum and Search --> : Restricting possible values of rand...
JCool451
05-30-2004, 03:54 AM
Take note that I'm doing this in c.
I know that one can restrict the values of the rand function by using %, which seems to work for numbers between 0 and whatever the number. What if I wanted a number between, let's say... 5 and 24?
Would I do something like "(rand()%19)+5"?
That is exactly what you should do.
bwkaz
05-30-2004, 06:08 PM
However, some versions of rand() don't have good randomness in the low-order bits of their result. On those systems (versions of glibc after about 2.0 are not among them, AFAIK), using rand() % some_number is not going to give you a random, even distribution from 0 to some_number-1, like you would expect.
But, it's probably as good as you're going to get. As long as you aren't depending on these numbers to do anything with encryption, or anything that requires true randomness, you're probably going to be OK. For example, choosing which state to go into next in an AI state machine is a great use of rand() % some_number; choosing a value to encrypt with a password when generating the string to put into /etc/shadow is not.
JCool451
06-06-2004, 12:25 AM
I'm making it as random as I possibly can, so I'm seeding the rand function with the current time. Does that help with the randomness? What I'm actually doing is developing an experience algorithm for an RPG, so it should be good enough for my purposes.
So what I want to do can be summed up as "(rand()%(max-min))+min" ?
bwkaz
06-06-2004, 08:06 AM
Originally posted by JCool451
I'm making it as random as I possibly can, so I'm seeding the rand function with the current time. Does that help with the randomness? Doing that does not change the randomness of your random number generator (in cryptographic terms). All it does is ensure that it starts from a different state each time the program runs (pseudo-RNGs like rand() will always generate the same sequence of numbers if they start with the same seed value, so if somebody's attacking your rand() stream of numbers, all they need to find out is the seed and they can reproduce the entire stream).
However, for your purposes, it's fine, yes.
So what I want to do can be summed up as "(rand()%(max-min))+min" ? Yep.