P粉6163836252023-09-06 00:26:00
This is not how you implement it. Your code checks if n is less than 7, which is the correct way.
Where does this statement come from? You could definitely test this premise...and see how possible it is.
This is real.
You can easily test the distribution of your implementation. You can call this function repeatedly and record the result you get and see how it changes over time. In statistics, the larger the sample size, the more reliable the results.
This is a code snippet that continuously executes the goAtChance
function and records the total number of calls and the number of true
results. Every 10 milliseconds, the results are updated on the page, including the ratio of the number of true
to the total. If all goes well, this ratio should approach 0.0007 over time.
const getRandomIntUnderN = (n) => Math.floor(Math.random() * n); const goAtChance = (n, m) => getRandomIntUnderN(m) < n; let [outTotal, outHits, outRatio] = document.querySelectorAll("span"); let hits = 0; // Number of results that are true let total = 0; // Total number of results requestAnimationFrame(function loop() { let deadline = performance.now() + 10; do { hits += goAtChance(7, 10000); // boolean coerces to 0 or 1 total++; } while (performance.now() < deadline); // Show the accumulated results outTotal.textContent = total; outHits.textContent = hits; outRatio.textContent = (hits / total).toFixed(8); requestAnimationFrame(loop); // Allow screen to update and then continue });
样本数:<span></span><br> 命中数:<span></span><br> 比例:<span></span>