Skip to content

Instantly share code, notes, and snippets.

@Daniel-Hug
Last active October 5, 2020 18:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daniel-Hug/f0fee168155f1af72c390030cc9be463 to your computer and use it in GitHub Desktop.
Save Daniel-Hug/f0fee168155f1af72c390030cc9be463 to your computer and use it in GitHub Desktop.
JS probability functions
// probability that the event with the passed probability will NOT occur
function complement(p) {
return 1 - p;
}
// probability that a and b will happen when neither outcome
// is affected by the other (accepts 1 or more arguments)
function intersectionOfIndependentEvents(a, b) {
var ret = a;
for (var i = 1; i < arguments.length; i++) {
ret *= arguments[i];
}
return ret;
}
// probability that a or b will happen when neither outcome
// is affected by the other (accepts 1 or more arguments)
function unionOfIndependentEvents(a, b) {
var ret = a;
for (var i = 1; i < arguments.length; i++) {
ret = ret + arguments[i] - ret * arguments[i];
}
return ret;
}
// returns probability of a sequence repeating any substring for
// repeatLength terms given that the sequence is seqLength terms long
// and is a random permutation with uniqueTermCount unique terms.
// See also: Find longest repeat: https://gist.github.com/Daniel-Hug/98ab6b17d77623e47329a5bf71229c17
function probabilityOfRepeatingThisLong(seqLength, repeatLength, uniqueTermCount) {
var arr = [];
var prob = 1 / Math.pow(uniqueTermCount, repeatLength);
var maxBlockLength = seqLength - repeatLength;
for (var i = 1; i < maxBlockLength; i++) {
arr.push(prob);
}
// fix: repeating this long with different periods are not independent events
return unionOfIndependentEvents.apply(null, arr);
}
@Daniel-Hug
Copy link
Author

intersection = probability that a and b will happen
Union = probability that a or b will happen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment