[swift-users] arc4random_uniform on Linux is missing from Foundation??

Jens Persson jens at bitcycle.com
Mon May 22 16:17:04 CDT 2017


Check out the generators (especially xoroshiro) on this site:

On Mon, May 22, 2017 at 6:54 PM, Saagar Jha via swift-users <
swift-users at swift.org> wrote:

>
> Saagar Jha
>
> On May 22, 2017, at 08:44, Edward Connell via swift-users <
> swift-users at swift.org> wrote:
>
> Any ideas when Foundation on Linux will support arc4random_uniform? This
> is kind of an important function.
> There doesn't seem to be any decent substitute without requiring the
> installation of libbsd-dev, which turns out to be messy. Currently I am
> doing this, but glibc random with mod does not produce good quality
> numbers, due to modulo bias.
>
>
> Modulo bias is easy to deal with, though, if you force random to produce a
> range that is a multiple of the range that you’re trying to produce:
>
> guard range > 0 else { return 0 }
> var random: Int
> repeat {
> random = Int(random())
> } while(random > LONG_MAX / range * range)
> return random % range
>
>
> Has anyone come up with a better solution to get a true uniform
> distribution that isn't super messy?
>
> import Foundation
>
> #if os(Linux)
> import Glibc
> #endif
>
>
> public func random_uniform(range: Int) -> Int {
> guard range > 0 else { return 0 }
> #if os(Linux)
>  return Int(random()) % range
> #else
> return Int(arc4random_uniform(UInt32(range)))
> #endif
> }
>
>
> Thanks, Ed
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170522/54b3de43/attachment.html>


More information about the swift-users mailing list