Example usage for java.util Random nextGaussian

List of usage examples for java.util Random nextGaussian

Introduction

In this page you can find the example usage for java.util Random nextGaussian.

Prototype

public synchronized double nextGaussian() 

Source Link

Document

Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.

Usage

From source file:org.polymap.core.runtime.cache.test.PerformanceCacheTest.java

public void testRandom() throws Exception {
    Timer timer = new Timer();
    int count = 0;
    Random random = new Random();
    ByteArrayLoader loader = new ByteArrayLoader();
    while (timer.elapsedTime() < 30000) {
        log.println("adding 1000 to " + cache.size());
        for (int i = 0; i < 10000; i++) {
            Integer key = new Integer((int) (Math.abs(random.nextGaussian()) * 400000));
            cache.get(key, loader);/*from   w  w w  . ja  v  a 2 s.  c  o m*/
            count++;
        }
    }
    long time = timer.elapsedTime();
    log.println("Loops: " + count + " in " + time + "ms -> " + (1000f * count / time) + "/s");
}

From source file:org.jlinda.core.coregistration.estimation.utils.MathUtils.java

/**
 * Gets a random number from a one dimensional Gaussian
 * distribution with the given mean and variance.
 *
 * @param randGenerator the random generator.
 * @param mean          the mean of the Gaussian
 * @param stdev         the standard deviation of the Gaussian
 * @return a random number from the specified distribution
 *///ww w.j  a v a  2 s . c o  m
public static double nextRandomGaussian(Random randGenerator, double mean, double stdev) {
    return mean + stdev * randGenerator.nextGaussian();
}

From source file:eu.amidst.core.exponentialfamily.EF_JointNormalGamma.java

/**
 * {@inheritDoc}/*  w  ww .j  a  v  a  2s .c om*/
 */
@Override
public EF_UnivariateDistribution randomInitialization(Random random) {

    double randomVar = random.nextDouble() * 2 + 1 + 0.01;

    double alpha = 10;
    double beta = randomVar * alpha;
    double mean = random.nextGaussian() * 10;
    double var = random.nextDouble() * 10 + 1;
    double precision = 1 / var;

    naturalParameters.set(EF_JointNormalGamma.MU_GAMMA, mean * precision);
    naturalParameters.set(EF_JointNormalGamma.MUSQUARE_GAMMA, -0.5 * precision);
    naturalParameters.set(EF_JointNormalGamma.GAMMA, -beta - 0.5 * precision * mean * mean);
    naturalParameters.set(EF_JointNormalGamma.LOGGAMMA, alpha - 0.5);

    this.fixNumericalInstability();
    this.updateMomentFromNaturalParameters();

    return this;
}

From source file:com.mapr.synth.TermGeneratorTest.java

@Test
public void speciesCounts() {
    final boolean transpose = false;

    // generate an example of species sampled on multiple days
    LongTail<Integer> terms = new LongTail<Integer>(0.5, 0.3) {
        int max = 0;

        @Override/*from w  w  w .  ja  v a  2 s. c om*/
        protected Integer createThing() {
            return ++max;
        }
    };

    // I picked seeds to get a good illustration ... want a reasonable number of species and surprises
    terms.setSeed(2);

    Random gen = new Random(1);
    SortedSet<Integer> vocabulary = Sets.newTreeSet();
    List<Multiset<Integer>> r = Lists.newArrayList();

    for (int i = 0; i < 2000; i++) {
        double length = Math.rint(gen.nextGaussian() * 10 + 50);
        Multiset<Integer> counts = HashMultiset.create();
        for (int j = 0; j < length; j++) {
            counts.add(terms.sample());
        }
        r.add(counts);
    }

    if (transpose) {
        for (Multiset<Integer> day : r) {
            vocabulary.addAll(day.elementSet());
        }

        System.out.printf("%d\n", vocabulary.size());
        for (Integer s : vocabulary) {
            String sep = "";
            for (Multiset<Integer> day : r) {
                System.out.printf("%s%s", sep, day.count(s));
                sep = "\t";
            }
            System.out.printf("\n");
        }
    } else {
        System.out.printf("%d\n", vocabulary.size());
        for (Multiset<Integer> day : r) {
            vocabulary.addAll(day.elementSet());
            String sep = "";
            System.out.printf("%s%s", sep, vocabulary.size());
            sep = "\t";
            for (Integer s : vocabulary) {
                System.out.printf("%s%s", sep, day.count(s));
                sep = "\t";
            }
            System.out.printf("\n");
        }

        Multiset<Integer> total = HashMultiset.create();
        for (Multiset<Integer> day : r) {
            for (Integer species : day.elementSet()) {
                total.add(species, day.count(species));
            }
        }
        String sep = "";
        System.out.printf("%s%s", sep, total.elementSet().size());
        sep = "\t";
        for (Integer s : vocabulary) {
            System.out.printf("%s%s", sep, total.count(s));
            sep = "\t";
        }
        System.out.printf("\n");
    }
}

From source file:org.lightjason.agentspeak.action.builtin.TestCActionMath.java

/**
 * test hypot//from   w  w w.j a v a 2s  . co m
 */
@Test
public final void hypot() {
    final Random l_random = new Random();
    final List<Double> l_input = IntStream.range(0, 100).mapToDouble(i -> l_random.nextGaussian()).boxed()
            .collect(Collectors.toList());

    final List<ITerm> l_return = new ArrayList<>();

    new CHypot().execute(false, IContext.EMPTYPLAN,
            l_input.stream().map(CRawTerm::from).collect(Collectors.toList()), l_return);

    Assert.assertArrayEquals(l_return.stream().map(ITerm::<Number>raw).toArray(),
            StreamUtils.windowed(l_input.stream(), 2, 2).mapToDouble(i -> Math.hypot(i.get(0), i.get(1)))
                    .boxed().toArray());
}

From source file:ru.mipt.pim.server.similarity.SuperBit.java

/**
 * Initialize SuperBit algorithm. Super-Bit depth N must be [1 .. dimension] and
 * number of Super-Bit L in [1 .. The resulting code length K = N * L The K
 * vectors are orthogonalized in L batches of N vectors
 * //from  ww  w.  j a v a  2  s  .co m
 * @param dimension
 *            data space dimension
 * @param depth
 *            Super-Bit depth [1 .. dimension]
 * @param superBitsAmount
 *            number of Super-Bit [1 ..
 */
public SuperBit(int dimension, int depth, int superBitsAmount) {
    this.dimension = dimension;
    if (dimension <= 0) {
        throw new IllegalArgumentException("Dimension dimension must be >= 1");
    }

    if (depth < 1 || depth > dimension) {
        throw new IllegalArgumentException("Super-Bit depth N must be 1 <= N <= dimension");
    }

    if (superBitsAmount < 1) {
        throw new IllegalArgumentException("Number of Super-Bit L must be >= 1");
    }

    // Input: Data space dimension dimension, Super-Bit depth 1 <= N <= dimension, number of
    // Super-Bit L >= 1,
    // resulting code length K = N * L

    // Generate a random matrix H with each element sampled independently
    // from the normal distribution
    // N (0, 1), with each column normalized to unit length. Denote H = [v1,
    // v2, ..., vK].
    int signatureDimension = depth * superBitsAmount;

    double[][] v = new double[signatureDimension][dimension];
    Random rand = new Random();

    for (int i = 0; i < signatureDimension; i++) {
        double[] vector = new double[dimension];
        for (int j = 0; j < dimension; j++) {
            vector[j] = rand.nextGaussian();
        }

        normalize(vector);
        v[i] = vector;
    }

    // for i = 0 to L - 1 do
    // for j = 1 to N do
    // w_{iN+j} = v_{iN+j}
    // for k = 1 to j - 1 do
    // w_{iN+j} = w_{iN+j} - w_{iN+k} w^T_{iN+k} v_{iN+j}
    // end for
    // wiN+j = wiN+j / | wiN+j |
    // end for
    // end for
    // Output: H = [w1, w2, ..., wK]

    double[][] hyperplanesArr = new double[signatureDimension][dimension];
    for (int i = 0; i <= superBitsAmount - 1; i++) {
        for (int j = 1; j <= depth; j++) {
            java.lang.System.arraycopy(v[i * depth + j - 1], 0, hyperplanesArr[i * depth + j - 1], 0,
                    dimension);

            for (int k = 1; k <= (j - 1); k++) {
                hyperplanesArr[i * depth + j - 1] = sub(hyperplanesArr[i * depth + j - 1],
                        product(dotProduct(hyperplanesArr[i * depth + k - 1], v[i * depth + j - 1]),
                                hyperplanesArr[i * depth + k - 1]));
            }

            normalize(hyperplanesArr[i * depth + j - 1]);

        }
    }

    this.hyperplanes = Arrays.stream(hyperplanesArr).map(ArrayRealVector::new)
            .toArray(size -> new RealVector[size]);
}

From source file:net.sf.jclal.classifier.WekaComitteClassifier.java

/**
 * Returns the probability that has the instance to belong to each class.
 *
 * @param instance The instance to test// w ww .  j  a  va 2 s .com
 * @return The probabilities for each class
 */
@Override
public double[] distributionForInstance(Instance instance) {
    try {

        double[] consensus = new double[instance.dataset().numDistinctValues(instance.classIndex())];

        double sizeCommittee = classifiers.length;

        for (int i = 0; i < sizeCommittee; i++) {

            /* modified here */

            /*double[] currentProb = classifiers[i]
                .distributionForInstance(instance);
                    
            for (int j = 0; j < consensus.length; j++) {
            consensus[j] += currentProb[j];
            }*/

            //FIRST MODIFIED VERSION

            /*Random random = new Random();
                    
            for (int j = 0; j < consensus.length; j++) {
            double cenas = random.nextGaussian();
                    
            if(cenas < 0)
                cenas = 0;
            else if(cenas > 1)
                cenas = 1;
                    
            consensus[j] += cenas;
            }*/

            //SECOND MODIFIED VERSION

            Random random = new Random();

            for (int j = 0; j < consensus.length; j++) {
                double cenas = random.nextGaussian();

                if (cenas < 0)
                    cenas = -0.48 * cenas;
                else
                    cenas = 0.48 + 0.48 * cenas;

                consensus[j] += cenas;
            }

        }

        for (int i = 0; i < consensus.length; i++) {
            consensus[i] /= sizeCommittee;
        }

        return consensus;

    } catch (Exception ex) {
        Logger.getLogger(VoteEntropyQueryStrategy.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;

}

From source file:org.xbib.elasticsearch.index.analysis.langdetect.LangdetectService.java

private double[] detectBlock(List<String> list, String text) throws LanguageDetectionException {
    // clean all non-work characters from text
    text = text.replaceAll(word.pattern(), " ");
    extractNGrams(list, text);//from   w  w w.  j a v  a  2 s  .  co m
    if (list.isEmpty()) {
        throw new LanguageDetectionException("no features in text");
    }
    double[] langprob = new double[langlist.size()];
    Random rand = new Random();
    Long seed = 0L;
    rand.setSeed(seed);
    for (int t = 0; t < n_trial; ++t) {
        double[] prob = initProbability();
        double a = this.alpha + rand.nextGaussian() * alpha_width;
        for (int i = 0;; ++i) {
            int r = rand.nextInt(list.size());
            updateLangProb(prob, list.get(r), a);
            if (i % 5 == 0) {
                if (normalizeProb(prob) > conv_threshold || i >= iteration_limit) {
                    break;
                }
            }
        }
        for (int j = 0; j < langprob.length; ++j) {
            langprob[j] += prob[j] / n_trial;
        }
    }
    return langprob;
}

From source file:hivemall.mix.server.MixServerTest.java

@Test
public void testSimpleScenario() throws InterruptedException {
    int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "3" }, MixServer.getOptions());
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);// w w w .j av  a  2 s.  c  o  m

    waitForState(server, ServerState.RUNNING);

    PredictionModel model = new DenseModel(16777216, false);
    model.configureClock();
    MixClient client = null;
    try {
        client = new MixClient(MixEventName.average, "testSimpleScenario", "localhost:" + port, false, 2,
                model);
        model.configureMix(client, false);

        final Random rand = new Random(43);
        for (int i = 0; i < 100000; i++) {
            Integer feature = Integer.valueOf(rand.nextInt(100));
            float weight = (float) rand.nextGaussian();
            model.set(feature, new WeightValue(weight));
        }

        Thread.sleep(5000L);

        long numMixed = model.getNumMixed();
        Assert.assertEquals("number of mix events: " + numMixed, numMixed, 0L);

        serverExec.shutdown();
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:hivemall.mix.server.MixServerTest.java

@Test
public void testSSL() throws InterruptedException {
    int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "3", "-ssl" },
            MixServer.getOptions());/*from   w w w. jav a 2 s .  c  o m*/
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);

    waitForState(server, ServerState.RUNNING);

    PredictionModel model = new DenseModel(16777216, false);
    model.configureClock();
    MixClient client = null;
    try {
        client = new MixClient(MixEventName.average, "testSSL", "localhost:" + port, true, 2, model);
        model.configureMix(client, false);

        final Random rand = new Random(43);
        for (int i = 0; i < 100000; i++) {
            Integer feature = Integer.valueOf(rand.nextInt(100));
            float weight = (float) rand.nextGaussian();
            model.set(feature, new WeightValue(weight));
        }

        Thread.sleep(5000L);

        long numMixed = model.getNumMixed();
        Assert.assertEquals("number of mix events: " + numMixed, numMixed, 0L);

        serverExec.shutdown();
    } finally {
        IOUtils.closeQuietly(client);
    }
}