Skip to content

Instantly share code, notes, and snippets.

@michaelrockhold
Last active February 18, 2019 00:23
Show Gist options
  • Save michaelrockhold/d668bee5614f4f9910e126c0ef057897 to your computer and use it in GitHub Desktop.
Save michaelrockhold/d668bee5614f4f9910e126c0ef057897 to your computer and use it in GitHub Desktop.
Swift code to use Marsaglia's method to generate a stream of standard normal random variables
//
// Marsaglia.swift
//
// Created by Michael Rockhold on 2/16/19.
// Copyright © 2019 Michael Rockhold. All rights reserved.
//
import Foundation
struct Marsaglia {
let mean: Double
let stdDev: Double
var spare: Double? = nil
var u: Double = 0
var v: Double = 0
var s: Double = 0
init(mean m:Double, stdDev d:Double) {
mean = m; stdDev = d
}
mutating func generateGaussianNoise() -> Double {
let drandmax = 1.0
func r() -> Double { return Double.random(in: (-1.0...1.0)) }
if let sp = spare {
spare = nil
return mean + stdDev * sp
}
repeat {
u = r() / drandmax * 2.0 - 1.0
v = r() / drandmax * 2.0 - 1.0
s = u * u + v * v
} while s >= 1.0 || s == 0.0
s = sqrt(-2.0 * log(s) / s)
spare = v * s
return mean + stdDev * u * s
}
}
@michaelrockhold
Copy link
Author

Call this like this:

var m = Marsaglia(mean:0.0, stdDev:1.0)
for _ in (0..<1000) {
print(m.generateGaussianNoise())
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment