random - ANSI C / rand() % 7 first value is always 3 -


this question has answer here:

so trying figure out special rand() mod k7 in c. in post said c rand() uses http://en.wikipedia.org/wiki/linear_congruential_generator don't see makes (mod k7) k-> scalar special algorithm associated ansi c.

so have following code:

#include <stdio.h> #include <time.h> #include <stdlib.h> #include <unistd.h>  void getrand(int* num1, int* num2, int* num3);   int main(int argc, const char * argv[]) {     int = 0;     (i = 0; < 100; i++) {          srand(time(null));         printf("%d\n", rand() % 7 );          sleep(1);     }     return 0; } 

this prints 3. if use n such 7 not divide n, better sequence of first values. still not random better 3 or c mod 7 = 3.

i deliberately made program way seed in loop show first value returns 3 regardless of seed.

yes random numbers xn n > 0 want x1 % 7 != x1 % 7 each xo.

ok, lets start looking @ more few data points:

#include <stdio.h> #include <time.h> #include <stdlib.h>   int main(int argc, const char * argv[]) {     size_t counters[7] = {0,0,0,0,0,0,0};     time_t tt = time(null);      //for (size_t = 0; < 7; i++) {     //  printf("result: %d count: %d\n", i, counters[i]);     //}      (size_t = 0; < 1000000; i++) {         srand(tt + i);         counters[rand() % 7] ++;     }      (size_t = 0; < 7; i++) {         printf("result: %d count: %d\n", i, counters[i]);     } } 

with this, on windows 7, visual studio 2013 compile c++ get

result: 0 count: 142894 result: 1 count: 142850 result: 2 count: 142848 result: 3 count: 142855 result: 4 count: 142854 result: 5 count: 142845 result: 6 count: 142854 

what get, because suspect you'll better result larger data set.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -