Skip to content

Instantly share code, notes, and snippets.

@gnh1201
Last active September 17, 2023 04:18
Show Gist options
  • Select an option

  • Save gnh1201/232bdb4e15bb230589505a65d9921562 to your computer and use it in GitHub Desktop.

Select an option

Save gnh1201/232bdb4e15bb230589505a65d9921562 to your computer and use it in GitHub Desktop.
probability_bit.js
function make_bit(p) {
if(p > 0) {
return (Math.random() / p) > 1.0);
} else {
return 0;
}
}
function make_bits(number_of_bits) {
var bits = [];
for(var i = 0; i <= number_of_bits; i++) {
bits.push(make_bit( parseFloat(i) / parseFloat(number_of_bits) ));
}
return bits;
}
/*
0001 = 1
0010 = 2
0011 = 3
0100 = 4
+ 0101 = 5
----------------
1111 = 15
*/
function make_bit(p) {
if(p > 0) {
cond = ((Math.random() / p) > 1.0);
} else {
cond = true;
}
return !cond;
}
function convert_bit(d) {
return (d == false) ? 0 : 1;
}
var stats = {}
for(var i = 0; i < 100000; i++) {
var bits = [convert_bit(make_bit(0/5)), convert_bit(make_bit(2/5)), convert_bit(make_bit(2/5)), convert_bit(make_bit(3/5))];
var binary = bits.join("");
var num = parseInt(binary, 2);
console.log(binary + " = " + num);
if(num in stats) {
stats[num]++;
} else {
stats[num] = 1;
}
}
console.log(JSON.stringify(stats));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment