Do you have a function (else than random) to find random dice(from 1 to 6) numbers(in C++) -


i writing code game 7 dices , have problem. if use random function(dice = rand()%6 + 1) realized probability instance sequence such 123456 (a sequence makes points in game) has higher probability out. mathematically, sequence has 1.54% probability show when use random function 100 millions iterations appears 5.4% of time!

that leads me question. know way randomize dice respect probability? or way fix problem anyway?

thanks in advance!

the problem facing known , natural result of using modulo operator random.

c++11 solves these problems providing not uniformly distributed random numbers several different types of distributions bernoulli distribution, normal distribution , poisson distribution.

the new header providing these generators , distributions random.

let's example: want have random number generator gives numbers , want have distribution shapes these numbers want them (uniformly, bernoulli ...).

#include <iostream> #include <random>  int main(){     std::mt19937(6473);    // random number generator using deterministic seed     std::uniform_int_distribution<int> dist(1,6);    // distribution gives random numbers in [0,99]      for(int i=0;i<10;i++){         std::cout << dist(mt) << std::endl;     } } 

this gives pseudo-random numbers uniformly distributed interval chose! c++11 provides more! provides real random number generator (see implementations more details) can use follows:

#include <iostream> #include <random>  int main(){     std::random_device rd;     std::mt19937 mt(rd());    // random number generator using non-deterministic random device     std::uniform_int_distribution<int> dist(1,6);    // distribution gives random numbers in [1,6]      for(int i=0;i<10;i++){         std::cout << dist(mt) << std::endl;     } } 

it easy provide real high quality random numbers distributed want , interval want using c++11. got knowlege topic talk of stephen t. lavavej (stl) held @ goingnative 2013 can watch on channel 9 , called rand() considered harmful.

fun fact: title reference essay great edsger wybe dijkstra called "go considered harmful." in dijkstra explained why no programmer should use goto statement.


Comments