title: Javascript random number with weighted probability
body: <p>I'm trying to create a function with the following signature:</p>
  
  <pre><code>function weightedRandom (target, probability) {
    // calculate weighted random number that is more likely to be near target value
    return value; // number from 0 to 1
  }
  </code></pre>
  
  <p>It should do the following:</p>
  
  <ul>
  <li>Generate random number from 0 to 1, but not including 1</li>
  <li>The probability of any given number being picked in that range is NOT evenly distributed</li>
  <li>There is a greater chance that the number picked is near the <strong>target</strong> value (target is also a value from 0 to 1)</li>
  <li>The probability curve would look like a bell curve, where the target value has the highest probability and the values around it taper down, but all values in the 0 to 1 range would still have a chance of getting picked.</li>
  <li>The weight of this chance can be adjusted with the <strong>probability</strong> value, where a value of 0 means there is no weighting applied to the randomness and 1 means that almost all numbers picked will be clustered right around the target value.</li>
  </ul>
  
  <p>For example, <code>weightedRandom(0.8, 0.2)</code> would result in a random value that is 20% likely to be clustered around the value 0.8, but could be any number from 0 up to 1. If the probability was 0.5, then even more of the resulting random values returned would be near 0.8. I think maybe there needs to be another parameter to define the width of the cluster (standard deviation?).</p>
  
  <p>I am not a mathematician, but I have been told to look at <a href="http://en.wikipedia.org/wiki/Beta_distribution" rel="nofollow noreferrer">Beta Distributions</a> as a possible tool to help:</p>
  
  <p><img src="https://i.stack.imgur.com/nE9ED.png" alt="enter image description here"></p>
  
  <p>I've found some NPM modules that have <code>beta</code> functions, but I'm not sure how to use them to solve this problem:</p>
  
  <ul>
  <li><a href="https://github.com/AndreasMadsen/mathfn" rel="nofollow noreferrer">https://github.com/AndreasMadsen/mathfn</a></li>
  <li><a href="https://github.com/jstat/jstat" rel="nofollow noreferrer">https://github.com/jstat/jstat</a></li>
  </ul>