import java.util.*; // T J Finney, 2001 // Not to be sold without my permission. class Stats { // static or class variables // random number generator private static Random rand = new Random(); // static or class methods // get uniformly distributed double in [0, 1] public static double getRand () { return rand.nextDouble(); } // get uniformly distributed integer in [0, N - 1] public static int getRandInt (int N) { return rand.nextInt(N); } // compute growth increment // uses logistic growth eqn // dN/dt = rN(1-N/K) // N = current size // r = annual growth rate // K = size limit public static double logistic (double N, double r, double K) { // calculate dN/dt return r * N * (1 - N / K); } public static void main (String [] args) { //test methods for (int i = 0; i < 5; i++) { System.out.println("Rand: " + Stats.getRand()); } System.out.print("RandInt: "); for (int i = 0; i < 50; i++) { System.out.print(Stats.getRandInt(2)); } System.out.println(); for (int i = 0; i < 5; i++) { System.out.println("Trial: " + Stats.trial(0.5)); } double[] numbers = {0, 1, 2, 3}; for (int i = 0; i < 5; i++) { System.out.println("Select: " + Stats.select(numbers, -1)); } for (int i = 0; i < 5; i++) { System.out.println("Zipf: " + Stats.zipf(3)); } } // select item using power law // arguments: // * array of numbers ni // * exponent p // probability of selecting array item: // p(ni) = k * (ni^p) // k is a normalisation constant // p(ni) = 0 if ni is zero, even when p < 0 // returns index in [0, array size - 1] public static int select (double[] nums, double p) { // make array of probabilities double[] probs = new double[nums.length]; for (int i = 0; i < probs.length; i++) { if (nums[i] == 0) { probs[i] = 0; } else { probs[i] = Math.pow(nums[i], p); } } // sum probabilities double sum = 0; for (int i = 0; i < probs.length; i++) { sum += probs[i]; } // obtain random number in range [0, sum] double r = sum * Stats.getRand(); // subtract probs until result negative // no of iterations gives required index int i; for (i = 0; i < probs.length; i++) { r -= probs[i]; if (r < 0) { break; } } return i; } // perform trial using uniform prob dist // p (probability) must be in [0, 1] public static boolean trial (double p) { if (p < 0) { p = 0; } if (p > 1) { p = 1; } if (rand.nextDouble() <= p) { return true; } else { return false; } } // select item using Zipf's law // parameter is size of ranked array // returns index in [0, array size - 1] public static int zipf (int size) { // make array of numbers double[] nums = new double[size]; for (int i = 0; i < nums.length; i++) { nums[i] = i + 1; } // get index using special case of power law return Stats.select(nums, -1.0); } }