is this correct? random
long GenerateRandom(long Min, long Max)
{
long Num;
srand(Max - Min);
Num = rand() + Min;
W_ErrorLog.WriteNumber("Number: ",Num, 16);
return Num;
}
every tiem i'm getting that Num = 2461 when pass (0, 800)... o.O
No, it is not correct. It might help if you reread the answers to your previous question on this topic. To recap srand seeds the random number generator. Seeding a random number generator sets which sequence of random numbers will be generated next. If you seed the random number generator and then get a random number you will always get the same "random" number if you always use the same seed value, since the seed value determines what numbers will be returned from the random number function.
Enigma
Enigma
ohhhh, ok... i didn't understand what ppl were saying about using the time thing for srand(). i didn't know it will return the same number if the same srand() number is passed to it.
should i just avoid the whole call to srand() and just use
random = min + rand() % (max-min)
should i just avoid the whole call to srand() and just use
random = min + rand() % (max-min)
Only seed the random number generator once.
rand()%n will generate a random number between 0 and n-1, but in most cases it will not have a completely uniform distribution, which you can see if you try to generate a lot of numbers in a certain range and count how often each number occurs.
rand()%n will generate a random number between 0 and n-1, but in most cases it will not have a completely uniform distribution, which you can see if you try to generate a lot of numbers in a certain range and count how often each number occurs.
Random numbers from rand() do have a uniform distribution. The AP above is wrong! The fact that each number didn't occur the exact same number of times, doesn't deter from the fact that it is an even distribution. In fact if they were equal then it wouldn't be random! If it were anything else, you'd see a triangle or bell curve shape or something else in the long run.
It is only psuedorandom however, so no it's not perfect.
This is what you want:
It is only psuedorandom however, so no it's not perfect.
This is what you want:
int main(){ srand(timeGetTime()); //Once, i.e. in main!!! for (int i=0; i<20; i++) { cout << GenerateRandom(500, 800) << endl; }}long GenerateRandom(long Min, long Max){ return Min + rand() % (Max-Min);}
[smile]
Quote:Original post by iMalc
Random numbers from rand() do have a uniform distribution. The AP above is wrong!
No, the AP is right. rand() is uniformly distributed, but rand()%x in general is not.
Suppose rand() returns a uniform distribution of 0, 1 or 2, then rand()%2 has twice as many 0s as it has 1s.
To generate uniformly distributed values in [min,max] you can use:
(rand () * (max-min) / RAND_MAX) + min
Be careful with this code, it breaks when RAND_MAX*(max-min) > MAX_INT ...
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement