Last active
February 19, 2019 10:58
-
-
Save Ima8/4f150594dc10b2f24dcbeae464e77e87 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const m = 10; // Number of tosses | |
| const n = 0.4; // Probability of observe | |
| const k = 3; // number of at most observe | |
| const testN = 20; //Run the simulation for at least 20 times | |
| const observe = "T"; | |
| let count = 0; | |
| let round = 0; | |
| console.log("Number of tosses: ", m); | |
| console.log("Observe: ", observe); | |
| console.log("Probability of observe: ", n); | |
| console.log("Number of at most observe: ",k); | |
| console.log("Number of simulation: ", testN); | |
| for (let i = 0; i < testN; i++){ | |
| start() | |
| } | |
| console.log("Total of at most %d %s = %d",k,observe,count); | |
| console.log("probability of at most %d %s: %d",k,observe,(count/testN)); | |
| function start() { | |
| const arrResult = [] | |
| for (let i = 0; i < m; i++) { | |
| arrResult.push(flip()) | |
| } | |
| // Sum the result from random | |
| let result = arrResult.reduce((sum, x) => { | |
| if (observe == x) { | |
| return sum + 1 | |
| } else { | |
| return sum | |
| } | |
| }, 0) | |
| if (result <= k) { | |
| count++; | |
| // console.log("Here, Observe %s = %d; %s",observe,result,arrResult); | |
| } else { | |
| // console.log("Observe %s = %d; %s",observe,result,arrResult); | |
| } | |
| console.log("Round %d: %s = %d; %s",++round,observe,result,arrResult); | |
| } | |
| function flip() { | |
| return Math.random().toFixed(8) > n ? "H" : "T" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment