[swift-users] Make getting a random number more intuitive

Joe Groff jgroff at apple.com
Thu Jan 21 15:57:46 CST 2016


> On Jan 21, 2016, at 1:24 PM, Jens Alfke via swift-users <swift-users at swift.org> wrote:
> 
> 
>> On Jan 21, 2016, at 1:00 PM, Erica Sadun via swift-users <swift-users at swift.org <mailto:swift-users at swift.org>> wrote:
>> 
>> * In terms of cross-platform random numbers, there are any number of third party libraries and you can use rand() on many platforms
> 
> rand() is deprecated because it uses a poor algorithm that doesn’t provide enough randomness. From the random(3) man page:
> 
>      The random() and srandom() functions have (almost) the same calling
>      sequence and initialization properties as the rand(3) and srand(3) func-
>      tions.  The difference is that rand(3) produces a much less random
>      sequence -- in fact, the low dozen bits generated by rand go through a
>      cyclic pattern.  All of the bits generated by random() are usable.  For
>      example, `random()&01' will produce a random binary value.
> 
> I’d forgotten that random()s sidekick function srandomdev() seeds the RNG with a cryptographic source of entropy, making it usable for secure purposes. So these would be good functions to implement a Swift RNG with.

Another important thing arc4random_uniform provides is a uniform distribution between 0 and an arbitrary upper bound. Naively constraining the output of random() by using '%' will give you a biased result if the bound isn't a power of 2.

-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160121/f0946c8a/attachment.html>


More information about the swift-users mailing list