Re: rand() and srand() broken?
Re: rand() and srand() broken?
- Subject: Re: rand() and srand() broken?
- From: Andrew Myrick <email@hidden>
- Date: Wed, 25 Nov 2009 09:38:08 -0800
I can't speak to the results you're seeing (perhaps it's worth filing a bug?), but have you considered seeding from a high quality entropy source with sranddev()? I modified your test program to call it inside and outside of the loop, and got what appeared to be reasonable results in both cases.
-Andrew
On Nov 25, 2009, at 9:26 AM, Derek Gaston wrote:
> Hello everyone... I've been struggling with rand and srand on OSX 10.6 and 10.5. It seems to me that something is terribly broken. Here is a short program I wrote to convince myself of that:
>
> #include <stdlib.h>
> #include <iostream>
>
> int main()
> {
> for(unsigned int i=0; i<100; i++)
> {
> srand(i+1);
> double value = rand()/(RAND_MAX + 1.0);
> std::cout<<value<<std::endl;
> }
> }
>
> This piece of code should generate 100 random numbers between 0 and 1... I am expecting that they be fairly spaced out as well...
>
> This is actually indicative of what we actually do in one of our applications (I know it doesn't usually make much sense to reseed all the time... but you're just going to have to trust me that it's necessary in our case ;-)
>
> Here is the output I get on Snow Leopard:
>
> 7.82637e-06
> 1.56527e-05
> 2.34791e-05
> 3.13055e-05
> 3.91318e-05
> 4.69582e-05
> 5.47846e-05
> 6.2611e-05
> 7.04373e-05
> 7.82637e-05
> 8.60901e-05
> 9.39164e-05
> 0.000101743
> 0.000109569
> 0.000117396
> 0.000125222
> 0.000133048
> 0.000140875
> .....
>
> Note how _not_ random they are! This is actually what we are seeing in our application!
>
> Running the _exact_ same code on Linux I get:
>
> 0.840188
> 0.700976
> 0.56138
> 0.916458
> 0.274746
> 0.135439
> 0.486904
> 0.352761
> 0.206965
> 0.565811
> 0.926345
> 0.7856
> 0.632643
> .....
>
> Notice how they are nice and random... and well spread out through the 0 to 1 range.
>
> Am I doing something wrong?? I've tested this on several Linux distros and it always works fine.... what is different about rand and srand on OSX?
>
> Thanks for any help!
>
> Derek
> _______________________________________________
> Do not post admin requests to the list. They will be ignored.
> Darwin-dev mailing list (email@hidden)
> Help/Unsubscribe/Update your Subscription:
>
> This email sent to email@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden