Generate a random float between 0 and 1

jini picture jini · Mar 2, 2011 · Viewed 61k times · Source

I'm trying to generate a random number that's between 0 and 1. I keep reading about arc4random(), but there isn't any information about getting a float from it. How do I do this?

Answer

Vladimir picture Vladimir · Mar 2, 2011

Random value in [0, 1[ (including 0, excluding 1):

double val = ((double)arc4random() / UINT32_MAX);

A bit more details here.

Actual range is [0, 0.999999999767169356], as upper bound is (double)0xFFFFFFFF / 0x100000000.