Compute an approximation to the natural logarithm. - Java java.lang

Java examples for java.lang:Math Calculation

Description

Compute an approximation to the natural logarithm.

Demo Code

/*//from   w w  w.jav a  2 s. c om
 * 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 {
    private static final int EXPONENT_OFFSET = 52;
    private static final int EXPONENT_BIAS = 1023;
    private static final double LN2 = Math.log(2);
    private static final int BITS = 16;
    private static final int MASK = (1 << BITS) - 1;
    private static final double[] LOG_TABLE = new double[1 << BITS];

    /**
     * Compute an approximation to the natural logarithm. Assumes
     * parameter is positive and finite.
     *
     * @param x parameter
     * @return <code>ln(x)</code>
     */
    public static double log(final double x) {
        assert x >= 0 && !Double.isInfinite(x) && !Double.isNaN(x);
        if (x == 0.0) {
            return Double.NEGATIVE_INFINITY;
        }
        final long t = Double.doubleToRawLongBits(x);
        final long lg = (t >>> EXPONENT_OFFSET) - EXPONENT_BIAS;
        final int mantissa = (int) (t >> (EXPONENT_OFFSET - BITS));
        final double mlg = LOG_TABLE[mantissa & MASK];
        return mlg + lg * LN2;
    }
}

Related Tutorials