Java Gaussian gaussian()

Here you can find the source of gaussian()

Description

Returns a real number with a standard Gaussian distribution.

License

Open Source License

Declaration

public static double gaussian() 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Random;

public class Main {
    private static Random random;

    /**/*from   w  ww  . ja  v a 2  s . c om*/
     * Returns a real number with a standard Gaussian distribution.
     */
    public static double gaussian() {
        // use the polar form of the Box-Muller transform
        double r, x, y;
        do {
            x = uniform(-1.0, 1.0);
            y = uniform(-1.0, 1.0);
            r = x * x + y * y;
        } while (r >= 1 || r == 0);
        return x * Math.sqrt(-2 * Math.log(r) / r);

        // Remark:  y * Math.sqrt(-2 * Math.log(r) / r)
        // is an independent random gaussian
    }

    /**
     * Returns a real number from a gaussian distribution with given mean and stddev
     */
    public static double gaussian(double mean, double stddev) {
        return mean + stddev * gaussian();
    }

    /**
     * Return real number uniformly in [0, 1).
     */
    public static double uniform() {
        return random.nextDouble();
    }

    /**
     * Returns an integer uniformly between 0 (inclusive) and N (exclusive).
     * @throws IllegalArgumentException if <tt>N <= 0</tt>
     */
    public static int uniform(int N) {
        if (N <= 0)
            throw new IllegalArgumentException("Parameter N must be positive");
        return random.nextInt(N);
    }

    /**
     * Returns an integer uniformly in [a, b).
     * @throws IllegalArgumentException if <tt>b <= a</tt>
     * @throws IllegalArgumentException if <tt>b - a >= Integer.MAX_VALUE</tt>
     */
    public static int uniform(int a, int b) {
        if (b <= a)
            throw new IllegalArgumentException("Invalid range");
        if ((long) b - a >= Integer.MAX_VALUE)
            throw new IllegalArgumentException("Invalid range");
        return a + uniform(b - a);
    }

    /**
     * Returns a real number uniformly in [a, b).
     * @throws IllegalArgumentException unless <tt>a < b</tt>
     */
    public static double uniform(double a, double b) {
        if (!(a < b))
            throw new IllegalArgumentException("Invalid range");
        return a + uniform() * (b - a);
    }
}

Related

  1. addGaussianNoise(double[][] d, double m, double v)
  2. getGaussian()
  3. getGaussian(double aMean, double aVariance)
  4. hashToGaussian(int h)
  5. RandGaussian()