#ifndef CA_UWATERLOO_ALUMNI_DWHARDER_RATIO #define CA_UWATERLOO_ALUMNI_DWHARDER_RATIO // Author: Douglas Wilhelm Harder // Copyright (c) 2012 by Douglas Wilhelm Harder. All rights reserved. // Reference: Donald E. Knuth, "The Art of Computer Programming, Vol. 2, Seminumerical Algorithms", 3rd Ed., Addison Wesley, Toronto, 1998, p.130-2. // On successive calls to randn_ratio(), this function returns // a random standard normal value (a mean of zero and standard deviation of one). #include #include double randn_ratio() { while ( 1 ) { double u1 = drand48(); double u2 = drand48(); double s = sqrt( 8.0/exp(1.0) ) * (u2 - 0.5)/u1; double ss = s*s; if ( ( ss <= 5.0 - 4.0*exp(0.25)*u1 ) || ( ( ss < 4.0*exp(-1.35)/u1 + 1.4 ) && ( ss <= -4.0/log( u1 ) ) ) ) { return s; } } } #endif