My math is weak so excuse me if I am mistaken.

Ignore the cast to double for a moment.

You suggest:
 x = x * n / sysRandomMax;

I suggest:
x = (double)  x / ( (double) (1 + sysRandomMax / n )) ;

So to the the upper limit suppose:
sysRandomMax = 99
n = 3
x = 99

x*n/sysRandomMax = 3
x/(1+sysRandomMax/n) = 2 + remainder = in integer math 2

Notice that for equation 1 the range is wrong because getting a three
returned is very unlikely but possible.

I threw the cast to double in there because I was getting some weird integer
math round off error where I always was getting 0 for the equation

I was using unsigned long instead of integer because of carelessness.

Dave


"Danny Epstein" <[EMAIL PROTECTED]> wrote in message
news:68559@palm-dev-forum...
>
> > unsigned long RandomNum(unsigned long n)
>
> SysRandom only returns 15 bits of random data, so using a 32-bit argument
> for the desired range is potentially confusing. If you pass in a large
value
> for n, you'll get large results, but some of the values between zero and
n-1
> will never be returned. OTOH, the way you're using n within the function
> would require a cast if it was declared as a 16-bit argument.
>
> > {
> >  static Boolean initialized = false;
> >
> >  unsigned long x;
> >  if (initialized == false) {
> >   initialized = true;
> >   SysRandom(TimGetTicks());
> >  }
> >  if (n == 0)
> >   n = 1;
> >
> >  x = SysRandom(0) ;
>
> Storing a 16-bit (15, actually) in a 32-bit variable. So far so good...
>
> >  x = (double)  x / ( (double) (1 + sysRandomMax / n )) ;
>
> Why are you using doubles? What I mean is why are you using floating
point?
> The "sysRandomMax / n" expression will round down. I'm not sure if I
> understand this statement. AFAICT, what you're trying to do,
mathematically
> speaking, is:
>
> SysRandom(0) * n / sysRandomMax
>
> If you limit n to be in the [0..32767] range, then you can do this using
> 32-bit integer math:
>
> x = x * n / sysRandomMax;
>
> Note that this doesn't mind n being zero. Many people use:
>
> SysRandom(0) % n;
>
> despite the fact that it isn't uniform, particularly for large n. If n is
a
> power of two, you can use masking, for example:
>
> SysRandom(0) & 0x001F;
>
> returns a random number in the [0..31] range.
>
> >
> >  return x;
> > }
>
>



-- 
For information on using the Palm Developer Forums, or to unsubscribe, please see 
http://www.palmos.com/dev/tech/support/forums/

Reply via email to