<p>I want to implement a method that returns <code>true</code> with probability of <code>n/m</code> Probability returns <code>false</code>. </p>
<p>For example, I want to get <code>true</code> with a probability of 7/10000. </p>
<p>To achieve this, I first obtain a random integer
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 the
goAtChance
function and records the total number of calls and the number oftrue
results. Every 10 milliseconds, the results are updated on the page, including the ratio of the number oftrue
to the total. If all goes well, this ratio should approach 0.0007 over time.