From: <ma...@os...> - 2003-04-18 15:34:28
|
Rats. So it's the int casting that's causing all the trouble. I will look into making a better random number generator for ints then. Anyone have any good ones? :) Mark On 18 Apr, Motoyuki KAWABA wrote: > Hi, > > To decrease values of the 1st argument of get_random() doesn't look > good fixing, because (int)get_random(MAX_VALUE) rarely returns > MAX_VALUE. > > Here is the definition of (int)get_random(). > > (int)get_random(MAX_VALUE) > = (int)(get_percentage() * MAX_VALUE) > = (int)((double)rand() / (double)RAND_MAX * MAX_VALUE) > > where rand() returns [0 .. RAND_MAX]. > > Only when rand() returns RAND_MAX, (int)get_random(MAX_VALUE) can return > MAX_VALUE, because casting to integer is equivalent to a > floor-function in this case. (That probability is 1/2147483647 under > RedHat9.) > > I've tried the next program which just counts up the frequencies of > generated numbers. > ------------- > #include <stdio.h> > #include <stdlib.h> > > double get_percentage(); > long long get_random(long long max); > > #define MAX_VALUE 5 /* Maximum value */ > > unsigned int hist[MAX_VALUE+1]; > > main() { > unsigned long i = 0; > > for (i = 0; i <= MAX_VALUE; i++) > hist[i] = 0; > > for (i = 0; i < 100000; i++) > hist[(int)get_random(MAX_VALUE)]++; > > for (i = 0; i <= MAX_VALUE; i++) > printf("%d %d\n", i, hist[i]); > } > > /* Derived from common/common.c */ > long long get_random(long long max) > { > return (long long) (get_percentage() * (double) max); > } > > double get_percentage() > { > return (double) rand() / (double) RAND_MAX; > } > ------------- > Here is the output of the sample program. > $ ./xxx > 0 19925 > 1 20205 > 2 19952 > 3 19884 > 4 20034 > 5 0 <- MAX_VALUE > ------------- > I don't know whether get_percentage() should really return [0.0 > .. 1.0]. But at least it may be necessary to make another function for > integer random number generation. > > For example, > > /* returns [0 .. max] */ > long long get_random2(long long max) > { > return (long long) (get_percentage2() * (double) (max + 1)); > } > > /* returns [0 .. 1.0) */ > double get_percentage2() > { > return (double) rand() / ((double) RAND_MAX + 1.0); > } > ------------- > > Thanks. > ---------- > Motoyuki KAWABA > FUJITSU LABORATORIES LTD. > ka...@la... |