Last active
April 17, 2016 08:50
-
-
Save udaken/c265112b8245b970f510b49daed746e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GaussianNoise | |
{ | |
double z0, z1; | |
bool generate; | |
Random random; | |
public GaussianNoise() | |
{ | |
random = new Random(); | |
} | |
public GaussianNoise(Random random) | |
{ | |
if (random == null) | |
throw new ArgumentNullException(); | |
this.random = random; | |
} | |
public double Generate(double average = 0.0, double variance = 1.0) | |
{ | |
const double twoPi = 2.0 * Math.PI; | |
generate = !generate; | |
if (!generate) | |
return z1 * variance + average; | |
double u1, u2; | |
do | |
{ | |
u1 = random.NextDouble(); | |
u2 = random.NextDouble(); | |
} while (u1 <= Double.Epsilon); | |
var v1 = Math.Sqrt(-2.0 * Math.Log(u1)); | |
var v2 = twoPi * u2; | |
z0 = v1 * Math.Cos(v2); | |
z1 = v1 * Math.Sin(v2); | |
return z0 * variance + average; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment