Example usage for java.lang Math log

List of usage examples for java.lang Math log

Introduction

In this page you can find the example usage for java.lang Math log.

Prototype

@HotSpotIntrinsicCandidate
public static double log(double a) 

Source Link

Document

Returns the natural logarithm (base e) of a double value.

Usage

From source file:gedi.util.math.stat.distributions.PoissonBinomial.java

private void preprocess() {
    int n = pp.length;
    m = n + 1;//from  w  ww.  j a v a  2s .c  o  m
    int nextPowerOf2 = Integer.highestOneBit(m);
    if (nextPowerOf2 != m)
        nextPowerOf2 <<= 1;
    m = nextPowerOf2;
    n = m - 1;

    int ins = 0;
    int start = 0;
    for (int i = 1; i < pp.length; i++) {
        if (Math.abs(pp[i] - pp[start]) > 1E-10) {
            if (i - start > 1) {
                double p = pp[start];
                pp[ins++] = -(i - start);
                pp[ins++] = p;
            } else {
                pp[ins++] = pp[i - 1];
            }
            start = i;
        }
    }

    if (pp.length - start > 1) {
        double p = pp[start];
        pp[ins++] = -(pp.length - start);
        pp[ins++] = p;
    } else {
        pp[ins++] = pp[pp.length - 1];
    }

    double delta = 2 * Math.PI / m;
    z = new Complex[m];
    z[0] = new Complex(1, 0);

    for (int i = 1; i <= Math.ceil(n / 2.0); i++) {
        double tt = i * delta;

        //         for(int j=0;j<pp.length;j++)
        //         {
        //            double pj=j<opp.length?opp[j]:0;
        //            double ax=1-pj+pj*Math.cos(tt);
        //            double bx=pj*Math.sin(tt);
        //            double tmp1=Math.sqrt(ax*ax+bx*bx);
        //            double tmp2=Math.atan2(bx,ax); //atan2(x,y)
        //            c1o+=Math.log(tmp1);
        //            c2o+=tmp2;
        //         }

        double c1 = 0.00;
        double c2 = 0.00;
        for (int j = 0; j < ins; j++) {
            double pj = pp[j];
            double f = 1;
            if (pj < 0) {
                f = -pj;
                pj = pp[++j];
            }

            double ax = 1 - pj + pj * Math.cos(tt);
            double bx = pj * Math.sin(tt);
            double tmp1 = Math.sqrt(ax * ax + bx * bx);
            double tmp2 = Math.atan2(bx, ax); //atan2(x,y)
            c1 += Math.log(tmp1) * f;
            c2 += tmp2 * f;
        }
        z[i] = new Complex(Math.exp(c1) * Math.cos(c2), Math.exp(c1) * Math.sin(c2));
        z[z.length - i] = z[i].conjugate();
    }
    FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD);
    z = fft.transform(z, TransformType.FORWARD);
}

From source file:de.tudarmstadt.ukp.teaching.uima.nounDecompounding.ranking.MutualInformationBased.java

/**
 * Calculates the weight for a split/* w w  w  .  ja v a 2  s .  c  om*/
 * 
 * @param split
 * @return
 */
private float calcRank(Split split) {
    double total = 0;
    double count = 0;

    if (split.getSplits().size() == 1) {
        // Entropy for single words
        SplitElement w = split.getSplits().get(0);
        double p = this.freq(w).doubleValue() / FREQUENCY.doubleValue();

        return (float) ((-1) * p * Math.log(p));
    }

    for (int i = 1; i < split.getSplits().size(); i++) {
        // Mutual Information for splits.

        SplitElement w1 = split.getSplits().get(i - 1);
        SplitElement w2 = split.getSplits().get(i);

        double a = this.freq(w1, w2).multiply(FREQUENCY).doubleValue();
        double b = this.freq(w1).multiply(this.freq(w2)).doubleValue();
        double mutal;

        if (a == 0d) {
            mutal = 0d;
        } else {
            mutal = Math.log(a / b);
        }

        total += mutal;
        count++;
    }

    return (float) (total / count);
}

From source file:com.analog.lyric.dimple.solvers.core.parameterizedMessages.DirichletParameters.java

@Override
public double evalEnergy(Value value) {
    final double[] x = value.getDoubleArray();

    final int n = _alphaMinusOne.length;
    if (x.length != n) {
        throw new DimpleException("Argument does not contain %d-dimensional real joint value", n);
    }/*from www .ja va2 s  .  c  o  m*/

    double sum = 0.0, xSum = 0.0;

    if (isSymmetric()) {
        for (int i = n; --i >= 0;) {
            final double xi = x[i];
            if (xi <= 0) {
                return Double.POSITIVE_INFINITY;
            }

            sum -= Math.log(xi);
            xSum += xi;
        }

        sum *= _alphaMinusOne[0];
    } else {
        for (int i = n; --i >= 0;) {
            final double xi = x[i];
            if (xi <= 0) {
                return Double.POSITIVE_INFINITY;
            }

            sum -= (_alphaMinusOne[i]) * Math.log(xi); // -log(x_i ^ (a_i-1))
            xSum += xi;
        }
    }

    if (!DoubleMath.fuzzyEquals(xSum, 1, SIMPLEX_THRESHOLD * n)) // Values must be on the probability simplex
    {
        return Double.POSITIVE_INFINITY;
    }

    return sum;
}

From source file:gedi.util.math.stat.distributions.GeneralizedExtremeValueDistribution.java

public static GeneralizedExtremeValueDistribution fitDataByMoments(double[] data, int start, int end) {
    int n = end - start;
    if (n < 2)
        throw new RuntimeException("Too few data!");
    Arrays.sort(data, start, end);

    // compute moments
    final double[] b = new double[3];
    for (int j = 1; j <= n; j++) {
        int index = j - 1 - start;
        b[0] += data[index];//w w  w.  j  ava2s.  c  o m
        b[1] += data[index] * ((j - 1.0) / (n - 1.0));
        b[2] += data[index] * ((j - 1.0) / (n - 1.0)) * ((j - 2.0) / (n - 2.0));
    }
    b[0] /= n;
    b[1] /= n;
    b[2] /= n;

    // solve parameters
    UnivariateFunction f = new UnivariateFunction() {
        public double value(double k) {
            return (3 * b[2] - b[0]) / (2 * b[1] - b[0]) - (1 - Math.pow(3, -k)) / (1 - Math.pow(2, -k));
        }
    };
    double k;

    if (Math.signum(f.value(-0.5)) != Math.signum(f.value(0.5)))
        k = UnivariateSolverUtils.solve(f, -0.5, 0.5);
    else {
        double c = (2 * b[1] - b[0]) / (3 * b[2] - b[0]) - Math.log(2) / Math.log(3);
        k = 7.859 * c + 2.9554 * c * c;
    }

    double g = Gamma.gamma(1 + k);
    double alpha = ((2 * b[1] - b[0]) * k) / (g * (1 - Math.pow(2, -k)));
    double xi = b[0] + alpha * (g - 1) / k;

    double location = xi;
    double scale = alpha;
    double shape = -k;

    return new GeneralizedExtremeValueDistribution(location, scale, shape);
}

From source file:com.analog.lyric.dimple.factorfunctions.Multinomial.java

@Override
public final double evalEnergy(Value[] arguments) {
    int index = 0;
    if (!_NParameterConstant) {
        _N = arguments[index++].getInt(); // First argument is N parameter
        if (_N < 0)
            return Double.POSITIVE_INFINITY;
        _negativeLogFactorialN = -org.apache.commons.math3.special.Gamma.logGamma(_N + 1);
    }/*from   w  ww  .j a  v  a  2s.com*/

    final double[] alpha = arguments[index++].getDoubleArray(); // Next argument is the probability parameter vector
    final int dimension = alpha.length;

    if (arguments.length - index != dimension)
        throw new DimpleException(
                "Number of count variables must equal the dimension of the parameter vector.");

    int countSum = 0;
    double parameterSum = 0;
    double sum = _negativeLogFactorialN;
    for (int i = 0; i < dimension; i++) {
        final double alphai = alpha[i];
        if (alphai < 0)
            return Double.POSITIVE_INFINITY;
        parameterSum += alphai;

        final int x = arguments[index++].getInt(); // Remaining arguments are discrete count variables
        if (x < 0)
            return Double.POSITIVE_INFINITY;
        countSum += x;

        double negativeXLogAlphai;
        if (alphai == 0 && x == 0)
            negativeXLogAlphai = 0;
        else
            negativeXLogAlphai = -x * Math.log(alphai);
        sum += negativeXLogAlphai + org.apache.commons.math3.special.Gamma.logGamma(x + 1);
    }
    if (countSum != _N)
        return Double.POSITIVE_INFINITY;

    final double energy = sum + _N * Math.log(parameterSum);
    if (energy != energy) // Faster isNaN
        return Double.POSITIVE_INFINITY;

    return energy;
}

From source file:com.opengamma.analytics.financial.model.volatility.curve.FXVannaVolgaVolatilityCurveModel.java

private double getD1(final double s, final double k, final double t, final double rd, final double rf,
        final double sigma, final double sqrtT) {
    return (Math.log(s / k) + t * (rd - rf + 0.5 * sigma * sigma)) / sigma / sqrtT;
}

From source file:com.itemanalysis.psychometrics.irt.estimation.ItemFitG2.java

public void compute() {
    int validRowCount = 0;
    initializeExpectedFrequencies();/*  w w  w . j av  a2s. com*/

    //For debugging
    //        System.out.println(printContingencyTable("ORIGINAL TABLE"));

    condenseTable();

    //For debugging
    //        System.out.println(printContingencyTable("CONDENSED TABLE"));

    double r = 0;
    G2 = 0;
    double expectedFrequency = 0;
    for (int i = 0; i < numberOfBins; i++) {
        if (validRow[i]) {
            for (int j = 0; j < numberOfCategories; j++) {
                r = table[i][j] + .001;//Add small amount to avoid taking log of zero
                expectedFrequency = expectedValues[i][j] + .001;//Add small amount to avoid taking log of zero
                G2 += r * Math.log(r / expectedFrequency);

                //For debugging
                //                    System.out.println("i: " + i + "  j: " + j + "  R: " + r + " EF: " + expectedFrequency );
            }
            validRowCount++;
        }
    }

    G2 = G2 * 2.0;
    dfG2 = ((double) validRowCount) * ((double) numberOfCategories - 1.0);

    try {
        ChiSquaredDistribution chiSquaredDistribution = new ChiSquaredDistribution(dfG2);
        pvalueG2 = 1.0 - chiSquaredDistribution.cumulativeProbability(G2);
    } catch (Exception ex) {
        pvalueG2 = Double.NaN;
    }

}

From source file:edu.byu.nlp.stats.SymmetricDirichletMultinomialMatrixMAPOptimizable.java

/**
 * Equation 53 from http://research.microsoft.com/en-us/um/people/minka/papers/dirichlet/minka-dirichlet.pdf
 *//*from ww w  . jav a  2s .c  om*/
private static double computeLogLikelihood(double[][] data, double alpha, double[] perIDataSums, double gammaA,
        double gammaB, int N, int K) {

    double alphaK = alpha * K;

    double llik = 0;

    // gamma priors
    if (gammaA > 0 && gammaB > 0) {
        llik += ((gammaA - 1) * Math.log(alpha)) - gammaB * alpha;
    }

    for (int i = 0; i < N; i++) {
        // first  term numerator
        llik += Gamma.logGamma(alphaK);
        // first term denominator
        llik -= Gamma.logGamma(perIDataSums[i] + alphaK);
        // second term
        for (int k = 0; k < K; k++) {
            // second term numerator
            llik += Gamma.logGamma(data[i][k] + alpha);
            // second term denominator (factored out and precomputed)
        }
    }

    // this comes from the denominator of the second term
    // which can be factored out of the inner loop into 
    // prod_i prod_k (1/gamma(alpha_k))
    llik -= Gamma.logGamma(alpha) * N * K;

    return llik;
}

From source file:com.opengamma.analytics.math.interpolation.LogNaturalCubicMonotonicityPreservingInterpolator1D.java

@Override
public Interpolator1DDataBundle getDataBundle(final double[] x, final double[] y) {
    Validate.notNull(y, "y");
    final int nData = y.length;
    final double[] logY = new double[nData];
    for (int i = 0; i < nData; ++i) {
        ArgumentChecker.isTrue(y[i] > 0., "y should be positive");
        logY[i] = Math.log(y[i]);
    }//from  w  w  w .  j  a va 2 s  .c o m
    return new Interpolator1DLogPiecewisePoynomialDataBundle(new ArrayInterpolator1DDataBundle(x, logY, false),
            new MonotonicityPreservingCubicSplineInterpolator(new LogNaturalSplineHelper()));
}

From source file:es.ucm.fdi.ac.outlier.Hampel.java

/**
 * Ugly lookup of 'k' given alpha. Alpha must be either 0.01 or 0.05
 * for this to work as expected.//w  w  w .ja  va  2s .  com
 */
private static double analyticK(int n, double alpha) {
    double k;
    double logN = Math.log(n);
    double sqrtTwoLogN = Math.sqrt(2 * logN);
    double z_n_alpha = sqrtTwoLogN - Math.log(alpha / 2) / sqrtTwoLogN
            - (Math.log(logN) + Math.log(4 * Math.PI)) / (2 * sqrtTwoLogN);

    if (alpha == 0.05) {
        if ((n % 2) == 0) {//N even
            k = 1.483 * z_n_alpha + 21.61 * Math.pow(n + 1, -0.8655);
        } else {
            k = 1.483 * z_n_alpha + 14.43 * Math.pow(n - 3, -0.7939);
        }

        return k;

    } else if (alpha == 0.01) {
        if ((n % 2) == 0) {//N even
            k = 1.483 * z_n_alpha + 41.39 * Math.pow(n, -0.9143);
        } else {
            k = 1.483 * z_n_alpha + 24.48 * Math.pow(n - 5, -0.8236);
        }

        return k;
    } else {
        return Double.NaN;
        //            throw new IllegalArgumentException(
        //                    "Alpha IS RESTRICTED to be 0.01 or 0.05 ");
    }
}