Stupid question, but how exactly can we use NormalDistribution to generate an array of random numbers? The doc indicates the next method takes what I assume is a RandomNumberGenerator (for rng) but I haven’t figured out how to pass it properly yet.
A simple example would be much appreciated!

1 Like

This seems to work:

import TensorFlow
var rng = ARC4RandomNumberGenerator(seed: UInt64(1))
let dist = NormalDistribution<Double>(mean: 0, standardDeviation: 1)
var numbers: [Double] = []
let len = 1000
for _ in 0 ..< len {
    numbers.append( &rng))

Looked up in unit tests


The RandomDistribution protocol (which NormalDistribution and other distributions conform to) is pretty barebones right now. For now, you can use sth like the following:

import TensorFlow

extension RandomDistribution {
    // Returns a batch of samples.
    func next<G: RandomNumberGenerator>(
        _ count: Int, using generator: inout G
    ) -> [Sample] {
        var result: [Sample] = []
        for _ in 0..<count {
            result.append(next(using: &generator))
        return result

    // Returns a batch of samples, using the global Threefry RNG.
    func next(_ count: Int) -> [Sample] {
        return next(count, using: &

let dist = NormalDistribution<Float>(mean: 100, standardDeviation: 10)
// [98.81818, 110.83851, 103.91379, 100.8439, 100.6089]

Thank you both!
@vova I was in the code source and it never occurred to me to go look at the tests, will remember next time.

1 Like