Theoretical analysis of algorithms that return true or false, based on the study of given probabilities
P粉026665919
P粉026665919 2023-09-05 19:57:42
0
1
527

I want to implement a method that returns true with probability of n/m Probability returns false.

For example, I want to get true with a probability of 7/10000.

To achieve this, I first obtain a random integer n< code> that is less than 10000 from the function getrandomintundern< code>. i then determine if n< (7 1), and so, return true< code>, otherwise false< < p>

here my implementation:

 0 included while n not const getrandomintundern="(n)" => { rn="Math.random()" * math.trunc(rn) } opportunity of a truthy value m goatchance="(n," m)=">" getrandomintundern(m) an 7‰ to true console.log(goatchance(7, 10000))< pre> 

my question is: is it okay for me only judge whether 1) achieve expected perfect probability?

on one hand, numbers 1 7 are discrete enough in range 10000: there seems be bias makes returning likely. other since can get purely random number probabilities affected by which choose value. it [1,2,3,4,5,6,7], [21,22,23,24,25,26,27], [23,55,3,66,762,92,123] or anything number.

so, view correct? < div>

P粉026665919
P粉026665919

reply all (1)
P粉616383625

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.

How to test

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 thegoAtChancefunction and records the total number of calls and the number oftrueresults. Every 10 milliseconds, the results are updated on the page, including the ratio of the number oftrueto 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 });
样本数:
命中数:
比例:
    n<>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!