Skip to content

Instantly share code, notes, and snippets.

@brannondorsey
Created October 4, 2018 19:43
Show Gist options
  • Save brannondorsey/dc4cfe00d6b124aebd3277159dcbdb14 to your computer and use it in GitHub Desktop.
Save brannondorsey/dc4cfe00d6b124aebd3277159dcbdb14 to your computer and use it in GitHub Desktop.
Discrete probability distribution sampling in JavaScript
// MIT License
//
// (c) 2018 Brannon Dorsey <brannon@brannondorsey.com>
//
// 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.
// draw a discrete sample (index) from a probability distribution (an array of probabilities)
// probs will be rescaled to sum to 1.0 if the values do not already
function sample(probs) {
const sum = probs.reduce((a, b) => a + b, 0)
if (sum <= 0) throw Error('probs must sum to a value greater than zero')
const normalized = probs.map(prob => prob / sum)
const sample = Math.random()
let total = 0
for (let i = 0; i < normalized.length; i++) {
total += normalized[i]
if (sample < total) return i
}
}
const counts = {}
for (let i = 0; i < 1000000; i++) {
let index = sample([0.2, 0.2, 0.8, 0.8])
if (!counts.hasOwnProperty(index)) counts[index] = 0
counts[index]++
}
const numTrials = Object.values(counts).reduce((num, total) => num + total, 0)
for (key in counts) {
console.log(`${key}: ${counts[key] / numTrials}`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment