`rand` broken on osx
I'm trying to generate random integers, but they are always the same each time I run the program. For instance, if I have the one-line program (that I called rand.nit)
print(1000.rand)
then, on my computer, I always get 483:
[graphs] blondin_al [~/Applications/nit/lib/graphs]
$ nit rand.nit
483
[graphs] blondin_al [~/Applications/nit/lib/graphs]
$ nit rand.nit
483
[graphs] blondin_al [~/Applications/nit/lib/graphs]
$ nit rand.nit
483
[graphs] blondin_al [~/Applications/nit/lib/graphs]
$ nit rand.nit
483
Even if I add the srand command before running the program, I still always get 483.
What am I doing wrong?
Hi,
If you do call srand (which should not be necessary since it is automatically called since PR #916), you should indeed get different values, which do seem to work on my machine
$ ./rand
657
$ ./rand
509
The only difference I can spot is that you're using the interpreter, and well, he might very well be broken.
Though, on my machine there seems to be no such problem:
$ nit rand.nit
12
$ nit rand.nit
369
$ nit rand.nit
229
So, I'm not sure, if I recall correctly, you work on OSX right ? This would surprise me but this could be an environment-related issue. If someone could test this too on a mac, we'd be sure (ping @Tagachi)
Yes, I'm on Mac OS 10.10.3 (Yosemite).
But even when I do nitc rand.nit && ./rand, I still get the same numbers.
It looks like srand is marked as obsolete on OS X. They recommend to use arc4random instead for rand, but it cannot be seeded and won't produce the same result. Still there is no reason it doesn't work, it must be a bug in the OS, searching for srand broken on OS X yields a lot of results.
@ablondin It's an ugly workaround but you can define locally a method to access arc4random:
fun arc4random: Int `{ return arc4random(); `}
Linking with #1388.
Or easier
redef fun rand: Int do return 9
http://dilbert.com/strip/2001-10-25