Mel
Mel

Reputation: 2075

I fear that arc4random has betrayed me

I have code that pics a random number from 0 to 1. I am seeing that the number 1 is coming up far more times then the number 0 then I would think to be statistically possible.

This is my code:

int shipNumber = arc4random() % 2;

Should this code work? Am I just going crazy?

Upvotes: 6

Views: 968

Answers (2)

spacehunt
spacehunt

Reputation: 823

You might be seeing modulo bias.

Upvotes: 0

Cajunluke
Cajunluke

Reputation: 3113

That code should work.

What I suspect you're seeing is truly random (or, at least, sufficiently random) and your brain is trying to find patterns. (Everybody's brain tries to find patterns everywhere. That's how you're reading this. The issue is there are no patterns in randomness [that being pretty much the definition] for your brain to latch on to, so it invents some.)

If you really want to check your output for randomness, you'll need to do a statistical analysis of some kind or other.

Upvotes: 5

Related Questions