Compute an approximately geometric distribution on n items with decay parameter p. - Java java.lang

Java examples for java.lang:Math Calculation

Description

Compute an approximately geometric distribution on n items with decay parameter p.

Demo Code

/*//w ww  .  j  av a 2 s  .  c  o m
 * Copyright (c) 2014. Real Time Genomics Limited.
 *
 * Use of this source code is bound by the Real Time Genomics Limited Software Licence Agreement
 * for Academic Non-commercial Research Purposes only.
 *
 * If you did not receive a license accompanying this file, a copy must first be obtained by email
 * from support@realtimegenomics.com.  On downloading, using and/or continuing to use this source
 * code you accept the terms of that license agreement and any amendments to those terms that may
 * be made from time to time by Real Time Genomics Limited.
 */
//package com.java2s;

public class Main {
    /**
     * Compute an approximately geometric distribution on n items with decay
     * parameter p.
     *
     * @param n number of items
     * @param p decay rate (0<p<=1)
     * @return distribution
     */
    public static double[] geometric(final int n, final double p) {
        if (p <= 0 || p > 1) {
            throw new IllegalArgumentException();
        }
        final double[] r = new double[n];
        double v = 1.0;
        for (int k = 0; k < n; k++, v *= p) {
            r[k] = v;
        }
        return renormalize(r);
    }

    /**
     * Renormalize an array to make it a probability distribution.
     *
     * @param a relative frequencies
     * @return corresponding probability distribution
     */
    public static double[] renormalize(final int[] a) {
        double s = 0;
        for (final int v : a) {
            s += v;
        }
        s = 1 / s;
        final double[] p = new double[a.length];
        for (int k = 0; k < a.length; k++) {
            p[k] = s * a[k];
        }
        return p;
    }

    /**
     * Renormalize an array to make it a probability distribution.
     *
     * @param a relative frequencies
     * @return corresponding probability distribution
     */
    public static double[] renormalize(final double[] a) {
        double s = 0;
        for (final double v : a) {
            s += v;
        }
        s = 1 / s;
        final double[] p = new double[a.length];
        for (int k = 0; k < a.length; k++) {
            p[k] = s * a[k];
        }
        return p;
    }
}

Related Tutorials