// CS 1538 Fall 2009 // This class has some methods to generate random variates import java.util.Random; import java.lang.Math; public class RandDist { private static boolean haveOne = false; private static double Z1, Z2; // Transform U(0,1) into the exponential distribution using the // inverse transform technique. public static double exponential(double lambda) { double R = Math.random(); double mean = 1/lambda; double nextran = -mean * Math.log(R); return nextran; } // Transform U(0,1) into the normal distribution using the polar // technique. Note that this technique generates two values at // a time, so the second is saved and used at the next call. public static double normal(double mean, double stddev) { if (haveOne) { haveOne = false; return (mean + stddev*Z2); } else { double R1 = Math.random(); double R2 = Math.random(); double theta = 2 * Math.PI * R2; double left = Math.sqrt((-2)*Math.log(R1)); Z1 = left*Math.cos(theta); Z2 = left*Math.sin(theta); haveOne = true; return (mean + stddev*Z1); } } // Transform U(0,1) into the Erlang distribution using convolution. This // distribution is the sum of k exponential variates, each with mean 1/k*theta. // Using some algebra as explained in the text and notes, we can calculate the // variate a bit more efficiently. public static double erlang(int k, double theta) { double R = 1.0; for (int i = 1; i <= k; i++) { R = R * Math.random(); } double logR = Math.log(R); return ((-1/(k*theta)) * logR); } // Discrete Uniform distribution, as discussed in lecture public static int uniform(int low, int high) { double R = Math.random(); return (low + (int)((high - low + 1)*R)); } }