Skip to content

rand broken on osx #1387

Open
Open

Description

@ablondin

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?

Activity

  1. lbajolet commented on May 25, 2015

    @lbajolet
    Contributor

    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)

  2. ablondin commented on May 25, 2015

    @ablondin
    ContributorAuthor

    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.

  3. xymus commented on May 25, 2015

    @xymus
    Contributor

    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.

  4. privat commented on May 25, 2015

    @privat
    Member

    Or easier

    redef fun rand: Int do return 9
    

    http://dilbert.com/strip/2001-10-25

  5. changed the title [-]How does `rand` work?[/-] [+]`rand` broken on osx[/+] on Jul 14, 2015
  6. added a commit that references this issue on Aug 7, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions