- Home /
Normal distribution random
I have been trying to figure out how to get random that follows normal distribution. But I just don't know how to get it done using unityscript.
I would like to have a function that would take two parameters minimum and maximum value and then return a normalized random from that range.
Something like:
NormalizedRandom(0,10)
0-1: *
1-2: ****
2-3: *********
3-4: ***************
4-5: ******************
5-6: *******************
6-7: ***************
7-8: ********
8-9: ****
9-10: *
This is not a Unity question. A Google search will give you a number of solutions that meet your criteria. One link here.
Answer by oferei · Jan 12, 2014 at 09:54 PM
There's a decent C# implementation here (of the Marsaglia polar method). Look for NextGaussianDouble. Replace "r.NextDouble()" with Unity's "Random.value" and voila, you have a standard normal distribution.
By saying standard I mean that the mean (average) is 0 and the standard deviation is 1. You can easily adjust it to any mean and standard deviation: simply multiply the result by the standard deviation and add the mean. (standard * stdDev + mean)
Now, the last step is to provide a function that returns a number inside a range. This would be a good time to mention that the normal distribution has no bounds. The function usually returns values that are close to the mean, but theoretically it can return any value. So what can we do? My suggestion is to use the three-sigma rule. Around 99.7% of all generated values should be no farther than 3 sigmas from the mean.
So we can choose our sigma to be one third of the difference between the mean and the desired limits.
Something like this Boo-like pseudo code:
def NormalizedRandom(minValue, maxValue):
mean = (minValue + maxValue) / 2
sigma = (maxValue - mean) / 3
return nextRandom(mean, sigma)
One question remains: what to do with values beyond 3 sigmas? A few ideas come to mind:
Discard. Throw the value away and generate another one. (Repeat until in range)
Move to edge. I.e., if it's greater than 3 sigmas - set it to exactly 3 sigmas
Flatten. Discard the value and generate a new value inside the range with even distribution
There's no right answer that won't skew the distribution a little bit. But for most purposes any of these three ideas should do the trick.
That seems to be exactly what I wanted. Discarding the value looks like the best and easiest option. I am not working on this project anymore thou :/ But if I ever continue, I can use your solution :)
Answer by Oneiros90 · May 25, 2020 at 02:18 PM
I know this is an old thread but I guess you would like a ready-to-use implementation of the awesome @oferei answer:
public static float RandomGaussian(float minValue = 0.0f, float maxValue = 1.0f)
{
float u, v, S;
do
{
u = 2.0f * UnityEngine.Random.value - 1.0f;
v = 2.0f * UnityEngine.Random.value - 1.0f;
S = u * u + v * v;
}
while (S >= 1.0f);
// Standard Normal Distribution
float std = u * Mathf.Sqrt(-2.0f * Mathf.Log(S) / S);
// Normal Distribution centered between the min and max value
// and clamped following the "three-sigma rule"
float mean = (minValue + maxValue) / 2.0f;
float sigma = (maxValue - mean) / 3.0f;
return Mathf.Clamp(std * sigma + mean, minValue, maxValue);
}
Answer by lancelot18 · Aug 19, 2017 at 11:35 PM
I know this is a really old thread, but because I searched for a day and couldn't find a function that calculates the inverse normal distribution function (which is what you want if you want to generate the random function you describe), I have implemented a solution for Unity here.
To use (for a beginner such as myself):
Copy all of the code into a new C# script called "PeterAcklamInverseCDF" and save. Include the code in the same object where your script that needs it is located.
Include
PeterAcklamInverseCDF CDF;
when defining variables in the code you are writing.In void Awake () (or in Void Start() if you prefer) include the line
CDF = gameObject.GetComponent<PeterAcklamInverseCDF> ();
Use the code by calling
CDF.NormInv(Random.value, mean, sigma)
where mean is the mean value of your distribution and sigma is the standard deviation of the distribution. Note that instead of calling Random.value, you can put in a probability from 0 to 1 and it will calculate the inverse normal distribution function.
The code is attached below:
/* Peter John Acklam Inverse CDF
An very cheap and accurate algorithm for computing the inverse normal cumulative distribution function.
Description:
This algorithm returns the x value of the inverse cumulative distribution function (AKA the quantile function or inverse CDF). The end result is an error less than 1.15E-9
for all |x| < 38. (x < -38 has a probability 2.885E-136, which is smaller than Unity’s floating point precision.
Designed by Peter John Acklam. Ported to Unity C# by James Armstrong.
Source: http://home.online.no/~pjacklam/notes/invnorm/
WayBack Archive: https://web.archive.org/web/20151030215612/http://home.online.no/~pjacklam/notes/invnorm/
This software is distributed under the MIT License:
MIT License
Copyright (c) 2016 James Armstrong
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PeterAcklamInverseCDF : MonoBehaviour {
// NormInv has two forms. This form allows for an offset normal distribution with a standard deviation different than 1.
// Three variables are required for this variant: probability, mean and standard deviation (sigma).
public float NormInv(float probability, float mean, float sigma){
float x = NormInv (probability);
return sigma * x + mean;
}
// NormInv has two forms. This form allows for an offset normal distribution with a standard deviation different than 1.
// One variable is required for this varient: only the probability. The mean is assumed to be 0 and the standard deviation is assumed to be 1.
public float NormInv(float probability){
// Define variables used in intermediate steps
float q = 0f;
float r = 0f;
float x = 0f;
// Coefficients in rational approsimations.
float[] a = new float[]{-3.969683028665376e+01f, 2.209460984245205e+02f, -2.759285104469687e+02f, 1.383577518672690e+02f, -3.066479806614716e+01f, 2.506628277459239e+00f};
float[] b = new float[]{-5.447609879822406e+01f, 1.615858368580409e+02f, -1.556989798598866e+02f, 6.680131188771972e+01f, -1.328068155288572e+01f};
float[] c = new float[]{-7.784894002430293e-03f, -3.223964580411365e-01f, -2.400758277161838e+00f, -2.549732539343734e+00f, 4.374664141464968e+00f, 2.938163982698783e+00f};
float[] d = new float[]{ 7.784695709041462e-03f, 3.224671290700398e-01f, 2.445134137142996e+00f, 3.754408661907416e+00f};
// Define break-points
float pLow = 0.02425f;
float pHigh = 1f - pLow;
// Verify that probability is between 0 and 1 (noninclusinve), and if not, make between 0 and 1
if (probability <= 0f) {
probability = Mathf.Epsilon;
} else if (probability >= 1f) {
probability = 1f - Mathf.Epsilon;
}
// Rational approximation for lower region.
if (probability < pLow){
q = Mathf.Sqrt (-2f * Mathf.Log (probability));
x = (((((c [0] * q + c [1]) * q + c [2]) * q + c [3]) * q + c [4]) * q + c [5]) / ((((d [0] * q + d [1]) * q + d [2]) * q + d [3]) * q + 1f);
}
// Rational approximation for central region.
if (pLow <= probability && probability <= pHigh){
q = probability - 0.5f;
r = q * q;
x = (((((a [0] * r + a [1]) * r + a [2]) * r + a [3]) * r + a [4]) * r + a [5]) * q / (((((b [0] * r + b [1]) * r + b [2]) * r + b [3]) * r + b [4]) * r + 1f);
}
// Rational approximation for upper region.
if (pHigh < probability){
q = Mathf.Sqrt(-2*Mathf.Log(1f - probability));
x = -(((((c [0] * q + c [1]) * q + c [2]) * q + c [3]) * q + c [4]) * q + c [5]) / ((((d [0] * q + d [1]) * q + d [2]) * q + d [3]) * q + 1f);
}
return x;
}
}
Where do all these magic numbers come from in lines 51 to 56?
Ugh! I don't have enough reputation to add a normal reply... so here goes.
$$anonymous$$y math stops well before this proof, as I only have a masters in physics, not a PhD in mathematics... I.e. I use the math but don't know why... probably why I don't have a PhD in physics... ANYWHO...
According to the the algorithm's designer, he uses two separate rational $$anonymous$$imax approximations. The process is described here:
(Unity won't let me upload the pdf... if someone else could that would be very nice.)
One approximation is used for the central region when the probability is greater than 0.02425 and less than 0.97575. The other approximation is used outside of those bounds given the CDF function is somewhat symmetric. The author describes the tails first being passed through a non-linear transform before the $$anonymous$$max approximation is applied.
According to the author, the coefficients were computed by another algorithm he wrote, an iterative algorithm that moves the nodes back and forth to $$anonymous$$imize the absolute value of the relative error in the rational approximation. (The nodes are the values of x for which the algorithm is exact, i.e., the values of x for which error in the algorithm is zero.) In other words, the equation was annealed to $$anonymous$$imize the error.
This approach is similar to how a Taylor Expansion works but doesn't require the function to be known... only specific points.
The author also references a more accurate algorithm, but I note that the accuracy is well beyond the precision of float.
https://www.jstor.org/stable/2347330
I hope this helps!