Skip to content

Instantly share code, notes, and snippets.

@0V
Last active October 23, 2018 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0V/b1ee70c8ec9175e9ce07db98ca0ae764 to your computer and use it in GitHub Desktop.
Save 0V/b1ee70c8ec9175e9ce07db98ca0ae764 to your computer and use it in GitHub Desktop.
Ranged Box–Muller's method for Unity
using UnityEngine;
/// <summary>
/// Box–Muller's method
/// </summary>
public class RandomBoxMuller
{
public static float Range(float min, float max)
{
while (true)
{
// N(range *0.16f, range.Center)
// Almost Result will be for min to max
float v = GetNext((max - min) * 0.16f, (min + max) * 0.5f);
if (min <= v && v <= max) return v;
}
}
/// <summary>
/// N(mu,sigma)
/// </summary>
/// <returns></returns>
public static float GetNext(float sigma = 1f, float mu = 0)
{
float rand1, rand2;
while ((rand1 = Random.value) == 0) ;
while ((rand2 = Random.value) == 0) ;
return Mathf.Sqrt(-2f * Mathf.Log(rand1)) * Mathf.Cos(2f * Mathf.PI * rand2) * sigma + mu;
}
private static float DestabilizeRange(float min, float max, float v) => (min + max) * v;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment