[mercury-users] a typeclassful random.m
Richard A. O'Keefe
ok at cs.otago.ac.nz
Tue Feb 20 08:43:24 AEDT 2007
I wrote that [0.0,1.0) is fine for some things,
but that for others returning 0.0 is a disastrous bug.
Evidently I was not clear enough, for
Ralph Becket <rafe at csse.unimelb.edu.au> wrote:
If you've got a [0.0, 1.0) RNG, can't you turn that into a (0.0, 1.0]
RNG by simply subtracting each result of the former from 1.0?
Sometimes. Other times returning 1.0 could also be a problem.
For example, suppose you are using a single random generator for
both integers, via
i = (int)(N * u); /* wanting [0,N) */
and at least one of the non-uniform distributions described below,
then the possibility of a 1 would foul up the integer generation
and the possibility of a 0 would foul up the other. Yes, you CAN
fix it by subtracting [0,1) from 1, but what is the excuse for
pushing that burden on the programmer, who is least able to deal
with it, rather than the library writer?
By the way, I'm curious: what sort of problems abhor a 0.0?
The classic one is the generation of exponential random variates:
e = -log(u); /* C syntax */
where u is uniform (but not zero). The Ada 95 reference manual recommends
a kluge:
e = -log(u + DBL_MIN); /* C syntax again */
The Becket kluge,
e = -log(1.0 - u);
would not work in Ada, because Ada allows both 0.0 and 1.0 as possible
results. I cannot imagine why. Point is, BOTH of these are more
complicated than just -log(u), making them harder to get right in the
first place, and more likely to be (mistakenly) 'corrected' to the
simpler form during maintenance.
Another example is the Box-Muller formula for random Gaussians:
g = sqrt(-2.0*log(u1))*cos((2.0*M_PI)*u2);
where u1 and u2 are uniform, and u1 had better not be zero.
There is a formula for the t distribution:
t = sqrt(k*pow(u1,-2.0/k)-2.0)*cos((2.0*M_PI)*u2);
where k is the degrees of freedom you want (k > 0), u1 and u2 are
uniform random variables, and u1 had better not be zero.
It is quite hard enough transcribing these formulas correctly without
having to patch around the deficiencies of the RNG.
--------------------------------------------------------------------------
mercury-users mailing list
Post messages to: mercury-users at csse.unimelb.edu.au
Administrative Queries: owner-mercury-users at csse.unimelb.edu.au
Subscriptions: mercury-users-request at csse.unimelb.edu.au
--------------------------------------------------------------------------
More information about the users
mailing list