get a random number from a normal distribution with a mean of 0 and a standard deviation of 1 in swift

To get a random number from a normal distribution with a mean of 0 and a standard deviation of 1 in swift, we can make use of the GKRandomSource and GaussianDistribution classes provided by the GameplayKit framework.

main.swift
import GameplayKit

// create a random source
let randomSource = GKARC4RandomSource()

// create a gaussian distribution
let gaussianDistribution = GKGaussianDistribution(randomSource: randomSource, mean: 0, deviation: 1)

// get a random number from the distribution
let randomNumber = gaussianDistribution.nextInt()
318 chars
11 lines

In the above code, we first create a GKRandomSource object using the ARC4 algorithm. We then create a GKGaussianDistribution object using the random source and the desired mean and standard deviation. Finally, we call the nextInt() method on the distribution object to get a random integer value. Since the distribution has a mean of 0 and a standard deviation of 1, the generated random number will also have these values in its distribution.

gistlibby LogSnag