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:com.analog.lyric.dimple.solvers.gibbs.customFactors.MultinomialBlockProposal.java

@Override
public BlockProposal next(Value[] currentValue, Domain[] variableDomain) {
    final DimpleRandom rand = activeRandom();

    double proposalForwardEnergy = 0;
    double proposalReverseEnergy = 0;
    int argumentIndex = 0;
    int argumentLength = currentValue.length;
    Value[] newValue = new Value[argumentLength];
    for (int i = 0; i < argumentLength; i++)
        newValue[i] = Value.create(variableDomain[i]);

    // Get the current alpha values
    double[] alpha;
    double[] alphaEnergy;
    double alphaSum = 0;
    if (_customFactor.isAlphaEnergyRepresentation()) {
        alphaEnergy = _customFactor.getCurrentAlpha();
        alpha = new double[alphaEnergy.length];
        for (int i = 0; i < alphaEnergy.length; i++) {
            alpha[i] = Math.exp(-alphaEnergy[i]);
            alphaSum += alpha[i];//from   w ww  .ja v a2  s.  com
        }
    } else {
        alpha = _customFactor.getCurrentAlpha();
        alphaEnergy = new double[alpha.length];
        for (int i = 0; i < alpha.length; i++) {
            alphaEnergy[i] = -Math.log(alpha[i]);
            alphaSum += alpha[i];
        }
    }
    if (alphaSum == 0) // Shouldn't happen, but can during initialization
    {
        Arrays.fill(alpha, 1);
        Arrays.fill(alphaEnergy, 0);
        alphaSum = alpha.length;
    }

    int nextN = _constantN;
    if (!_hasConstantN) {
        // If N is variable, sample N uniformly
        int previousN = currentValue[argumentIndex].getIndex();
        int NDomainSize = requireNonNull(variableDomain[0].asDiscrete()).size();
        nextN = rand.nextInt(NDomainSize);
        newValue[argumentIndex].setIndex(nextN);
        argumentIndex++;

        // Add this portion of -log p(x_proposed -> x_previous)
        proposalReverseEnergy += -org.apache.commons.math3.special.Gamma.logGamma(previousN + 1)
                + previousN * Math.log(alphaSum);

        // Add this portion of -log p(x_previous -> x_proposed)
        proposalForwardEnergy += -org.apache.commons.math3.special.Gamma.logGamma(nextN + 1)
                + nextN * Math.log(alphaSum);
    }

    // Given N and alpha, resample the outputs
    // Multinomial formed by successively sampling from a binomial and subtracting each count from the total
    // FIXME: Assumes all outputs are variable (no constant outputs)
    int remainingN = nextN;
    int alphaIndex = 0;
    for (; argumentIndex < argumentLength; argumentIndex++, alphaIndex++) {
        double alphai = alpha[alphaIndex];
        double alphaEnergyi = alphaEnergy[alphaIndex];
        int previousX = currentValue[argumentIndex].getIndex();
        int nextX;
        if (argumentIndex < argumentLength - 1)
            nextX = rand.nextBinomial(remainingN, alphai / alphaSum);
        else // Last value
            nextX = remainingN;
        newValue[argumentIndex].setIndex(nextX);
        remainingN -= nextX; // Subtract the sample value from the remaining total count
        alphaSum -= alphai; // Subtract this alpha value from the sum used for normalization

        double previousXNegativeLogAlphai;
        double nextXNegativeLogAlphai;
        if (alphai == 0 && previousX == 0)
            previousXNegativeLogAlphai = 0;
        else
            previousXNegativeLogAlphai = previousX * alphaEnergyi;
        if (alphai == 0 && nextX == 0)
            nextXNegativeLogAlphai = 0;
        else
            nextXNegativeLogAlphai = nextX * alphaEnergyi;

        // Add this portion of -log p(x_proposed -> x_previous)
        proposalReverseEnergy += previousXNegativeLogAlphai
                + org.apache.commons.math3.special.Gamma.logGamma(previousX + 1);

        // Add this portion of -log p(x_previous -> x_proposed)
        proposalForwardEnergy += nextXNegativeLogAlphai
                + org.apache.commons.math3.special.Gamma.logGamma(nextX + 1);
    }

    return new BlockProposal(newValue, proposalForwardEnergy, proposalReverseEnergy);
}

From source file:beast.math.distributions.GammaDistribution.java

/**
 * probability density function of the Gamma distribution
 *
 * @param x     argument/*  w w  w.  ja v a2 s.c o  m*/
 * @param shape shape parameter
 * @param scale scale parameter
 * @return pdf value
 */
public static double pdf(double x, double shape, double scale) {
    // return Math.pow(scale,-shape)*Math.pow(x, shape-1.0)/
    // Math.exp(x/scale + GammaFunction.lnGamma(shape));
    if (x < 0)
        return 0; // to make BEAUti plot continue
    //            throw new IllegalArgumentException();
    if (x == 0) {
        if (shape == 1.0)
            return 1.0 / scale;
        else
            return 0.0;
    }

    final double xs = x / scale;

    if (shape == 1.0) {
        return Math.exp(-xs) / scale;
    }

    final double a = Math.exp((shape - 1.0) * Math.log(xs) - xs - GammaFunction.lnGamma(shape));

    return a / scale;
}

From source file:hu.ppke.itk.nlpg.purepos.model.internal.HashSuffixGuesser.java

@Override
public Map<T, Double> getTagLogProbabilities(String word) {
    HashMap<T, Double> ret = new HashMap<T, Double>();
    // Set<T> tags = freqTable.get("").getLeft().keySet();
    // for (T tag : tags) {
    // ret.put(tag, getTagLogProbability(word, tag));
    // }// w w w  . j ava2 s  .c  om
    // return ret;
    Map<T, Double> probs = getTagProbabilities(word);
    for (Map.Entry<T, Double> entry : probs.entrySet()) {
        ret.put(entry.getKey(), Math.log(entry.getValue()));
    }
    return ret;
}

From source file:org.fhcrc.cpl.toolbox.gui.chart.PanelWithScatterPlot.java

/**
 * Create a scatterplot with the logs of the values passed in
 * @param xValues//from   w ww.j  a v  a  2 s .c  o m
 * @param yValues
 * @param dataSetName
 * @return
 */
public static PanelWithScatterPlot createPlotForLogValues(java.util.List<? extends Number> xValues,
        java.util.List<? extends Number> yValues, String dataSetName) {
    java.util.List<Double> xValuesLog = new ArrayList<Double>();
    java.util.List<Double> yValuesLog = new ArrayList<Double>();

    for (int i = 0; i < xValues.size(); i++) {
        xValuesLog.add(Math.log(xValues.get(i).doubleValue()));
        yValuesLog.add(Math.log(yValues.get(i).doubleValue()));
    }
    return new PanelWithScatterPlot(xValuesLog, yValuesLog, dataSetName);
}

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

private Double leftExtrapolateDerivative(final Interpolator1DDataBundle data, final Double value) {
    Validate.notNull(data, "data");
    Validate.notNull(value, "value");
    final double x = data.firstKey();
    final double y = data.firstValue();
    final double m = Math.log(y) / x;
    return m * Math.exp(m * value);
}

From source file:edu.stanford.muse.index.Summarizer.java

private void computeIDFForTermsInOneDoc(MultiDoc d, int totalDocs) {
    List<Posting> dfs = superdocToPostingsIndex.get(d);
    if (dfs == null)
        return;/*  w w  w.j a  va 2  s.com*/

    for (Posting p : dfs) {
        float docsWithThisTerm = termToSuperDocCountIndex.get(p.term);

        float idfForThisTerm = (float) Math.log(totalDocs / docsWithThisTerm);
        if (totalDocs == docsWithThisTerm) {
            idfForThisTerm = 0.01f;
        }
        p.idf = idfForThisTerm;
    }
}

From source file:com.joliciel.jochre.search.highlight.LuceneQueryHighlighter.java

public LuceneQueryHighlighter(JochreQuery jochreQuery, IndexSearcher indexSearcher) {
    try {// w  w  w. j  ava  2  s. com
        this.indexSearcher = indexSearcher;
        this.jochreQuery = jochreQuery;
        query = rewrite(jochreQuery.getLuceneQuery());
        queryTerms = new TreeSet<Term>();
        query.extractTerms(queryTerms);
        if (LOG.isTraceEnabled())
            queryTermList = new ArrayList<Term>(queryTerms);

        final IndexReader reader = indexSearcher.getIndexReader();
        // add 1 to doc count to ensure even terms in all docs get a very small weight
        docCountLog = Math.log(reader.numDocs() + 1);

        IndexReaderContext readerContext = reader.getContext();
        leaves = readerContext.leaves();

        // since the same terms might be contained in the query multiple times (e.g. once per field)
        // we only consider them once each by using a HashSet
        terms = new HashSet<BytesRef>();
        Map<BytesRef, Integer> termFreqs = new HashMap<BytesRef, Integer>();
        for (Term term : queryTerms) {
            terms.add(term.bytes());
            termFreqs.put(term.bytes(), 0);
        }

        termLogs = new HashMap<BytesRef, Double>();
        for (Term term : queryTerms) {
            int freq = termFreqs.get(term.bytes());
            freq += reader.docFreq(term);
            termFreqs.put(term.bytes(), freq);
        }
        for (BytesRef term : terms) {
            int freq = termFreqs.get(term);
            termLogs.put(term, Math.log(freq));
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * Goal is to return a reasonable string representation
 * of x, using at most width spaces.  (If the parameter width is
 * unreasonably big or small, its value is adjusted to
 * lie in the range 6 to 25.)/*from   w ww  . j  a  va  2 s  .  c  om*/
 *
 * @param x value to create string representation of.
 * @param width maximum number of spaces used in string representation, if possible.
 * @return a string representation for x.  If x is Double.NaN, "undefined" is returned.
 *         If x is infinite, "INF" or "-INF" is returned.
 */
public static String realToString(double x, int width) {
    width = Math.min(25, Math.max(6, width));
    if (Double.isNaN(x))
        return "undefined";
    if (Double.isInfinite(x))
        if (x < 0)
            return "-INF";
        else
            return "INF";
    String s = String.valueOf(x);
    if (Math.rint(x) == x && Math.abs(x) < 5e15 && s.length() <= (width + 2))
        return String.valueOf((long) x); // return string without trailing ".0"
    if (s.length() <= width)
        return s;
    boolean neg = false;
    if (x < 0) {
        neg = true;
        x = -x;
        width--;
        s = String.valueOf(x);
    }
    long maxForNonExp = 5 * (long) Math.pow(10, width - 2);
    if (x >= 0.0005 && x <= maxForNonExp && (s.indexOf('E') == -1 && s.indexOf('e') == -1)) {
        s = round(s, width);
        s = trimZeros(s);
    } else if (x > 1) { // construct exponential form with positive exponent
        long power = (long) Math.floor(Math.log(x) / Math.log(10));
        String exp = "E" + power;
        int numlength = width - exp.length();
        x = x / Math.pow(10, power);
        s = String.valueOf(x);
        s = round(s, numlength);
        s = trimZeros(s);
        s += exp;
    } else { // constuct exponential form with negative argument
        long power = (long) Math.ceil(-Math.log(x) / Math.log(10));
        String exp = "E-" + power;
        int numlength = width - exp.length();
        x = x * Math.pow(10, power);
        s = String.valueOf(x);
        s = round(s, numlength);
        s = trimZeros(s);
        s += exp;
    }
    if (neg)
        return "-" + s;
    else
        return s;
}

From source file:com.opengamma.analytics.math.ComplexMathUtils.java

/**
 * Returns the principal value of log, with z the principal argument of z defined to lie in the interval (-pi, pi]
 * @param z ComplexNumber/*w  w  w.j  a va2s .  c  o  m*/
 * @return The log
 */
public static ComplexNumber log(final ComplexNumber z) {
    ArgumentChecker.notNull(z, "z");
    return new ComplexNumber(Math.log(Math.hypot(z.getReal(), z.getImaginary())),
            Math.atan2(z.getImaginary(), z.getReal()));
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.graphconnectivity.iterative.wikipedia.algorithm.LinkInformationSequentialDisambiguation.java

private double computeLinkMeasureSimilarity(String target0, String target1) throws SimilarityException {
    if (target0.equals(target1)) {
        return 1.0;
    }//www.  j  a  v  a2 s.c  o m

    List<String> linksA;
    List<String> linksB;
    try {
        linksA = getIncomingLinks(target0);
        linksB = getIncomingLinks(target1);
    } catch (Exception e) {
        throw new SimilarityException();
    }

    int linksBoth = ListUtils.intersection(linksA, linksB).size();

    double a = Math.log(linksA.size());
    double b = Math.log(linksB.size());
    double ab = Math.log(linksBoth);
    double m = Math.log(linkInformationReader.getNumberOfSenses());

    double sr = (Math.max(a, b) - ab) / (m - Math.min(a, b));

    if (Double.isNaN(sr) || Double.isInfinite(sr) || sr > 1) {
        sr = 1;
    }

    sr = 1 - sr;

    return sr;

}