這不是你實現(xiàn)的方式。你的代碼檢查n是否小于7,這是正確的方式。
這個陳述是從哪里來的?你肯定可以測試這個前提...并看看它有多大可能性。
這是真的。
你可以很容易地測試你的實現(xiàn)的分布情況。你可以反復(fù)調(diào)用這個函數(shù)并記錄你得到的結(jié)果,然后看看它隨時間的變化。在統(tǒng)計學(xué)中,樣本的大小越大,結(jié)果越可靠。
這是一個代碼片段,它不斷執(zhí)行goAtChance
函數(shù)并記錄調(diào)用的總次數(shù)和true
結(jié)果的數(shù)量。每隔10毫秒,結(jié)果會在頁面上更新,包括true
數(shù)量與總數(shù)的比例。如果一切正常,這個比例隨時間應(yīng)該趨近于0.0007。
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 });
樣本數(shù):<span></span><br> 命中數(shù):<span></span><br> 比例:<span></span>