What happened to this randomization feature?

I give him 0 and 400, and he sometimes returns me values ​​above 400. This makes no sense.

- (float)randomValueBetween:(float)low andValue:(float)high {
    return (((float) arc4random() / RAND_MAX) * (high - low)) + low;
}

which is actually a fragment that I found on the net. Maybe someone can see a mistake there?

+5
source share
4 answers

The page forarc4random indicates that the return value can be anywhere in the range valid for u int32(i.e. 0 to (2**32)-1). This means that you will want to split into 0xFFFFFFFFinstead RAND_MAX, which I assume is less (it depends on the library, so you will need to check exactly what it is).

Your function should look like this:

- (float)randomValueBetween:(float)low andValue:(float)high {
    return (((float) arc4random() / 0xFFFFFFFFu) * (high - low)) + low;
}
+7
  • arc4random (2 ^ 32 - 1)
  • RAND_MAX (2 ^ 31 - 1)

, , , (high - low) 2 0 - 800.

+6

iPhone RAND_MAX 0x7fffffff (2147483647), arc4random() 0x100000000, (4294967296)/(2147483647) = 2..... 2 * (400-0) + 0 = 800! ,

+3

:

- (float)randomValueBetween:(float)low andValue:(float)high {
    return (arc4random() % * (high - low)) + low;
}

mod, ?

, float ( float), - ? .

0

All Articles