'use strict';

// MODULES //

var sqrt = require( '@stdlib/math/base/special/sqrt' );
var ln = require( '@stdlib/math/base/special/ln' );


// VARIABLES //

var ONE_THIRD = 1.0 / 3.0;


// MAIN //

/**
* Returns a pseudorandom number drawn from a gamma distribution.
*
* @private
* @param {Function} rand - PRNG for uniformly distributed numbers
* @param {Function} randn - PRNG for standard normally distributed numbers
* @param {PositiveNumber} alpha - shape parameter
* @param {PositiveNumber} beta - rate parameter
* @returns {PositiveNumber} pseudorandom number
*/
function gamma( rand, randn, alpha, beta ) {
	var flg;
	var x2;
	var v0;
	var v1;
	var c;
	var d;
	var u;
	var v;
	var x;

	d = alpha - ONE_THIRD;
	c = 1.0 / sqrt( 9.0*d );
	flg = true;
	while ( flg ) {
		do {
			x = randn();
			v = 1.0 + (c*x);
		} while ( v <= 0.0 );
		v = v * v * v;
		u = rand();
		x2 = x * x;
		v0 = 1.0 - (0.331*x2*x2);
		v1 = (0.5*x2) + (d*(1.0 - v + ln( v )));
		if (
			u < v0 ||
			ln( u ) < v1
		) {
			flg = false;
		}
	}
	return (1.0/beta) * d * v;
} // end FUNCTION gamma()


// EXPORTS //

module.exports = gamma;

'use strict';

// MODULES //

var sqrt = require( '@stdlib/math/base/special/sqrt' );
var ln = require( '@stdlib/math/base/special/ln' );


// VARIABLES //

var ONE_THIRD = 1.0 / 3.0;


// MAIN //

/**
* Returns a pseudorandom number drawn from a gamma distribution.
*
* @private
* @param {Function} rand - PRNG for uniformly distributed numbers
* @param {Function} randn - PRNG for standard normally distributed numbers
* @param {PositiveNumber} alpha - shape parameter
* @param {PositiveNumber} beta - rate parameter
* @returns {PositiveNumber} pseudorandom number
*/
function gamma( rand, randn, alpha, beta ) {
	var flg;
	var x2;
	var v0;
	var v1;
	var c;
	var d;
	var u;
	var v;
	var x;

	d = alpha - ONE_THIRD;
	c = 1.0 / sqrt( 9.0*d );
	flg = true;
	while ( flg ) {
		do {
			x = randn();
			v = 1.0 + (c*x);
		} while ( v <= 0.0 );
		v *= v * v;
		u = rand();
		x2 = x * x;
		v0 = 1.0 - (0.331*x2*x2);
		v1 = (0.5*x2) + (d*(1.0 - v + ln( v )));
		if (
			u < v0 ||
			ln( u ) < v1
		) {
			flg = false;
		}
	}
	return (1.0/beta) * d * v;
} // end FUNCTION gamma()


// EXPORTS //

module.exports = gamma;

Replace assignment