get a normally distributed random number in swift

To generate a normally distributed random number in Swift, we can make use of the GaussianRandomNumberGenerator class from the GameplayKit framework.

First, we need to create an instance of GaussianRandomNumberGenerator with a mean and standard deviation. The mean is the center of the range of values, while the standard deviation determines the spread of values.

main.swift
import GameplayKit

let mean: Double = 0.0 // center of range
let standardDeviation: Double = 1.0 // spread of values
let generator = GaussianRandomNumberGenerator(mean: mean, deviation: standardDeviation)
206 chars
6 lines

Once we have the generator, we can use the nextUniform() method to generate a normally distributed random number between -1 and 1.

main.swift
let randomNum = generator.nextUniform()
40 chars
2 lines

We can also scale this value to a desired range by multiplying it by the desired range and adding the minimum value.

Here's an example of generating a normally distributed random number between 0 and 10:

main.swift
let minValue = 0
let maxValue = 10
let scaledRandomNum = (randomNum * Double(maxValue - minValue)) + Double(minValue)
118 chars
4 lines

Now, scaledRandomNum will be a normally distributed random number between 0 and 10.

gistlibby LogSnag