c++ - Program with probability -


in event need generate probability, example bias coin 75% of tossing head , 25% tossing tail. conventionally, way:

#include <cstdlib> #include <iostream> #include <ctime> using namespace std;  int main() {     int heads=0, tails=0;     srand(time(null));     number = rand() % 100 + 1;  //generate random number 1 100           if (number <= 75) //75% chance                 heads++; //this head           else                 tails++; //this tail } 

this working code, when answered similar question on bias coin in user, of users mentioned multiple of 100. since random function generates uniform distribution, feels above code enough simulating probability event.

in past posts, user bathsheba mentioned somehting multiples of 100: program simulates coin toss bias coin wanted know possible problems in code in relation that.

my question is: above code acceptable code create simulation probability? or there flaws in these codes affect accuracy of simulated results. if above codes has flaws, correct way of implementing simulation probability?

edit: simulated test of 10,000,000 toss. generates @ probability of approximately 75.01%-75.07% chance tossing head. problems there when generating seemingly accurate result. (the generated results didn't seemed skewed)

is above code acceptable code create simulation probability? or there flaws in these codes affect accuracy of simulated results?

if "acceptable" depends on definition of acceptable. not correct sure operator % makes probability skewed because rand_max maximum value rand() can not equal k * 100 + 99 results in if imagine 100-length parts of 0-rand_max string can see last part not produce full range 0-99, have more numbers generates 0, 1, 2..., x not necessary x + 1, ..., 98, 99 ( 1 more occurrence each number in 0, 1, 2, ..., x). inaccuracy of approach increases bigger divisor doesn't divide range evenly.

if above codes has flaws, correct way of implementing simulation probability?

you can use boost or if can run c++11 can use standard library's uniform_int_distribution.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -