Generating random numbers in C -
while searching tutorials on generating random numbers in c found this topic
when try use rand() function without parameters, 0. when try use rand() function parameters, value 41. , whenever try use arc4random() , random() functions, lnk2019 error.
here's i've done:
#include <stdlib.h> int main() { int x; x = rand(6); printf("%d", x); } this code generates 41. going wrong? i'm running windows xp sp3 , using vs2010 command prompt compiler.
you should call srand() before calling rand initialize random number generator.
either call specific seed, , same pseudo-random sequence
#include <stdlib.h> int main () { srand ( 123 ); int random_number = rand(); return 0; } or call changing sources, ie time function
#include <stdlib.h> #include <time.h> int main () { srand ( time(null) ); int random_number = rand(); return 0; } in response moon's comment rand() generates random number equal probability between 0 , rand_max (a macro pre-defined in stdlib.h)
you can map value smaller range, e.g.
int random_value = rand(); //between 0 , rand_max //you can mod result int n = 33; int rand_capped = random_value % n; //between 0 , 32 int s = 50; int rand_range = rand_capped + s; //between 50 , 82 //you can convert float float unit_random = random_value / (float) rand_max; //between 0 , 1 (floating point) this might sufficient uses, worth pointing out in first case using mod operator introduces slight bias if n not divide evenly rand_max+1.
random number generators interesting , complex, said rand() generator in c standard library not great quality random number generator, read (http://en.wikipedia.org/wiki/random_number_generation definition of quality).
http://en.wikipedia.org/wiki/mersenne_twister (source http://www.math.sci.hiroshima-u.ac.jp/~m-mat/mt/emt.html ) popular high quality random number generator.
also, not aware of arc4rand() or random() cannot comment.
Comments
Post a Comment