Re: C-faq q13.20
- From: Ben Bacarisse <ben.usenet@xxxxxxxxx>
- Date: Sun, 19 Nov 2006 11:02:46 +0000
"Thomas Lumley" <thomas@xxxxxxxxxxx> writes:
One of the examples in q13.20 in the FAQ
(http://c-faq.com/lib/sd16.html, linked from
http://c-faq.com/lib/gaussian.html) seems to be wrong.
The full code is at that link. The part of the code that actually does
the work is
y = (double) rand() / (RAND_MAX + 1.0); /* 0.0 <= y < 1.0 */
bin = (y < 0.5) ? 0 : 1;
y = fabs(y - 1.0); /* 0.0 < y <= 1.0 */
y = std_dev * sqrt((-2.0) * log(y));
return bin ? (mean + y) : (mean - y);
Indeed. The above will not produce a distribution that is symmetric
about "mean" because the decision as to which side of the mean we
return is correlated to the size of the uniform random number y. One
needs either another random sample:
return rand() > RAND_MAX/2 ? mean + y : mean - y;
or (if the your source in random bits is rather precious) the decision
must be based on a bit or bits in the original sample that are not
correlated to the size of the original y:
int r = rand();
y = (double)(r + 1) / (RAND_MAX + 1);
y = std_dev * sqrt(-2 * log(y));
return r & 1 ? mean + y : mean - y;
I can't see the advantage of the fabs. I think the above allows y to
be as small as (randomly) possible whist remaining > 0. Of course,
this last version raises the question of the suitability of using the
bottom bits returned by rand() which was well thrashed out about a
year ago.
I should add that even then I don't think the result is normally
distributed (though it will at least be symmetrical).
--
Ben.
.
- Follow-Ups:
- Re: C-faq q13.20
- From: Thomas Lumley
- Re: C-faq q13.20
- From: CBFalconer
- Re: C-faq q13.20
- From: Ben Bacarisse
- Re: C-faq q13.20
- References:
- C-faq q13.20
- From: Thomas Lumley
- C-faq q13.20
- Prev by Date: Re: Overview
- Next by Date: Re: C-faq q13.20
- Previous by thread: Re: C-faq q13.20
- Next by thread: Re: C-faq q13.20
- Index(es):
Relevant Pages
|