15

I'm playing with an optimized game of life implementation in swift/mac_os_x. First step: randomize a big grid of cells (50% alive).

code:

for(var i=0;i<768;i++){
  for(var j=0;j<768;j++){
    let r = Int(arc4random_uniform(100))
    let alive = (aliveOdds > r)
    self.setState(alive,cell: Cell(tup:(i,j)),cells: aliveCells)
  }
}

I expect a relatively uniform randomness. What I get has definite patterns:

Large image

Zooming in a bit on the lower left:

zoomed in

(I've changed the color to black on every 32 row and column, to see if the patterns lined up with any power of 2).

Any clue what is causing the patterns? I've tried:

  • replacing arc4random with rand().
  • adding arc4stir() before each arc4random_uniform call
  • shifting the display (to ensure the pattern is in the data, not a display glitch)

Ideas on next steps?

Adam Matan
  • 128,757
  • 147
  • 397
  • 562
pmeyer
  • 643
  • 1
  • 5
  • 10
  • 1
    Very weird indeed, you could try a seeded random number generator like `drand48()` (seed with `srand48(Int)`) which is as good in randomness as `arc4random()` and returns a Double between 0 and 1 (exclusive). See also: http://nshipster.com/random/ – Kametrixom Jun 14 '15 at 16:09
  • 2
    I'm more and more suspicious that it isn't arc4rand at all... Still experimenting, I'll report back if I figure anything out. – pmeyer Jun 14 '15 at 16:17
  • 2
    Ok, this is now officially annoying. I can no longer reproduce the problem. I've had it for several days (mostly ignored it, as I was working on the simulation part). However, with the random generation code posted above, I am now getting what I'll call a uniform field. No clue. – pmeyer Jun 14 '15 at 16:23
  • I see, but at least you made a picture as proof ;). But are you sure you didn't change something relevant? Maybe checkout an older version just to see if it occurs again? – Kametrixom Jun 14 '15 at 16:27
  • That's what source code control is for... You might have a second thread that initialises arc4random () from time to time. Still weird. – gnasher729 Jun 14 '15 at 21:08
  • 1
    I'm hacking together a little life program and wasn't checking in. Ah, well. I did have a second thread in some versions, but even if I ran synchronously in the main thread I still had the problem. Not a big deal, as it is resolved, but annoying that I never root caused it. – pmeyer Jun 15 '15 at 00:30

1 Answers1

1
  1. You cannot hit period or that many regular non-uniform clusters of arc4random on any displayable set (16*(2**31) - 1).

These are definitely signs of the corrupted/unininitialized memory. For example, you are initializing 768x768 field, but you are showing us 1024xsomething field.

  1. Try replacing Int(arc4random_uniform(100)) with just 100 to see.
user1232690
  • 481
  • 5
  • 16