Last active
October 23, 2018 14:49
-
-
Save 0V/b1ee70c8ec9175e9ce07db98ca0ae764 to your computer and use it in GitHub Desktop.
Ranged Box–Muller's method for Unity
This file contains hidden or 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
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