Search code examples
ioscrandomfloating-pointarc4random

Generate a random float between 0 and 1


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?


Solution

  • 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.