bug in gamdev? (Random #'s with gamma distribution)


chris_torrence
08-03-2004, 04:47 PM
In Numerical Recipes in C (2nd ed, version 2.08, but also checked against 2.10), the "gamdev" routine in section 7.3 has the following lines of code:

do {
do {
do {
v1=ran1(idum);
v2=2.0*ran1(idum)-1.0;
} while (v1*v1+v2*v2 > 1.0);
y=v2/v1;

The first line in the inner loop looks incorrect. Shouldn't it be:

do {
do {
do {
v1=2.0*ran1(idum)-1.0;
v2=2.0*ran1(idum)-1.0;
} while (v1*v1+v2*v2 > 1.0);
y=v2/v1;

So both v1 and v2 are distributed between -1 and +1. This agrees with Knuth (Art of Comp Prog vol 2) p. 122.

Thanks very much.

-Chris Torrence
Senior Software Engineer
Research Systems, Inc.

Saul Teukolsky
08-03-2004, 05:49 PM
Hi Chris,

The Knuth method picks a point uniformly inside a circle. The NR method picks a point uniformly inside a semicircle. The ratio of the coordinates in either case has the same distribution - the methods are equivalent.

Best wishes,
Saul Teukolsky

chris_torrence
08-03-2004, 10:53 PM
Hi Saul,

Thanks very much for the reply. That makes perfect sense. I should have thought of that myself. Please ignore my bug email that I also sent.

Cheers,

Chris