Re: [PATCH] small glib fix.



Darin Adler <darin bentspoon com> writes:

> On Wednesday, May 30, 2001, at 03:35  PM, Damian Ivereigh wrote:
> 
> >> On Wednesday, May 30, 2001, at 02:21  PM, Anders Carlsson wrote:
> >>
> >>> Really? I just based it on the g_rand_boolean macro:
> >>>
> >>> #define g_rand_boolean(rand) (g_rand_int ((rand)) & (1<<15))
> >>>
> >>> Is that wrong too?
> >>
> >> On 30 May 2001 13:19:27 -0700, Darin Adler wrote:
> >> I think so.
> >
> > I don't think it makes much difference. If the g_rand_int() function
> > where truly random (i.e. each number had an equal chance of occuring,
> > regardless of what the last number was) then it would absolutely make no
> > difference (all your doing is selecting which bit to use). However I
> > would have thought that the least significant bit was more likely to
> > have a better spectral spread than the most significant bit.
> >
> > This is all dragging up college math that is a bit rusty.
> 
> My suggested version:
> 
> #define g_rand_boolean(rand) ((g_rand_int (rand) >> 15) & 1)
> 
> The g_rand_int() function is not "truly random". It's a pseudorandom
> number generator. But this is beside the point, because both the
> existing macro any my proposed changed macro use the 16th significant
> bit. Whether to use the most or least significant bit is not what I'm
> criticizing.
> 
> The issue is whether 0x8000 is a good value for a function that
> returns a "boolean" to return. the original function returns 0 half of
> the time and 0x8000 the other half of the time. I prefer to use 0 and
> 1 for boolean values.

I think returning 0/FALSE and 1/TRUE is good; returning other things
can get you into trouble when you have, say a bitfield:

 struct {
   guint is_on : 1;
 }

 foo->is_on = g_random_boolean()

You could also write:

 (g_rand_int (rand) & (1 << 15) != 0)

Which makes the boolean nature a little clearer.

> PS: The least significant bits are in pseudorandom number generators
> are often not very random, so decisions should always be influenced
> primarily by the most significant digits. This is mentioned in Chapter
> 3 of Knuth's Art of Computer Programming in his [section 3.6,
> principle vi] and many other places.

Note, however that observation is typically made in regards
to linear-congruential RNG's. Which g_random() / g_rand() 
is not. Though it certainly should't do any harm to use a 
higher bit.

                                        Owen





[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]