Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This post has been wikified, any user with enough reputation can edit it.
avatar image
8
Question by Firzenizer · Mar 21, 2013 at 10:08 PM · randommathnormalnormalized

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: *
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image robertbu · Mar 21, 2013 at 10:14 PM 0
Share

This is not a Unity question. A Google search will give you a number of solutions that meet your criteria. One link here.

3 Replies

· Add your reply
  • Sort: 
avatar image
27
Best Answer

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.

alt text

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:

  1. Discard. Throw the value away and generate another one. (Repeat until in range)

  2. Move to edge. I.e., if it's greater than 3 sigmas - set it to exactly 3 sigmas

  3. 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.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Firzenizer · Jan 13, 2014 at 03:06 PM 0
Share

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 :)

avatar image oferei · Jan 14, 2014 at 04:38 PM 0
Share

great. feel free to accept my answer. ;)

avatar image
7

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);
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

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):

  1. 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.

  2. Include PeterAcklamInverseCDF CDF; when defining variables in the code you are writing.

  3. In void Awake () (or in Void Start() if you prefer) include the line CDF = gameObject.GetComponent<PeterAcklamInverseCDF> ();

  4. 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;
     }
 }








Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image christoph_r · Aug 20, 2017 at 11:05 PM 0
Share

Where do all these magic numbers come from in lines 51 to 56?

avatar image lancelot18 · Aug 21, 2017 at 04:36 PM 1
Share

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:

https://academic.oup.com/comjnl/article/9/3/286/406298/The-Construction-of-$$anonymous$$inimax-Rational

(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!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

14 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Algorithm for number generation that is random but consistent 2 Answers

Random InitState not working with Coroutines / IEnumerator? 2 Answers

Having random operators in an equation? 1 Answer

How can i add 0.5 to a side of a block? 1 Answer

Squared vector divided by squared magnitude 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges