#!/usr/bin/perl
# Produces a random variable distributed according to the
# Gaussian Normal Distribution with user input mean and standard deviation.
# Based on "A Fast Normal Random Number Generator" by Joseph L. Leva, ACM 1992
# Ross A. Winters, 10/10/07

my $mean = $ARGV[0];
my $stdev = $ARGV[1];
my $reps = $ARGV[2];

my $s=0.449871;
my $t=-0.386595;
my $a=0.19600;
my $b=0.25472;
my $r1=0.27597;
my $r2=0.27846;
my $u, $v, $x, $y, $q;

if ($mean eq "" || $stdev eq "" || $reps eq "") {
    print "Usage: normVar.pl mean stdev reps<return>\n"; exit -1; }

srand (time() ^ ($$ + ($$ << 15)) );  # Random Seed

for (my $i=0;$i<$reps;$i++)
{
    print $mean + $stdev*&normvar,"\n";
}
exit 0;

sub normvar
{
  do
    {
    $u = rand 1; $v = rand 1;

    $v = 1.7156*($v - 0.5);
    $x = $u - $s;
    $y = (abs $v) - $t;
    $q = $x**2 + $y*($a*$y - $b*$x);

    if ( $q < $r1) { return $v/$u; }

    }
  while ( ($v**2 <= -4.0*($u**2)*log($u)) || ($q <= $r2) );

return $v/$u;
} 
