Java Code Examples for org.apache.commons.math.util.FastMath#floor()

The following examples show how to use org.apache.commons.math.util.FastMath#floor() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApproximatePoissonTreeLikelihood.java    From beast-mcmc with GNU Lesser General Public License v2.1 6 votes vote down vote up
static double getStirlingError(double z) {
    double ret;
    double z2;
    if (z < 15.0D) {
        z2 = 2.0D * z;
        if (FastMath.floor(z2) == z2) {
            ret = EXACT_STIRLING_ERRORS[(int)z2];
        } else {
            ret = Gamma.logGamma(z + 1.0D) - (z + 0.5D) * FastMath.log(z) + z - HALF_LOG_2_PI;
        }
    } else {
        z2 = z * z;
        ret = (0.08333333333333333D - (0.002777777777777778D - (7.936507936507937E-4D - (5.952380952380953E-4D - 8.417508417508417E-4D / z2) / z2) / z2) / z2) / z;
    }

    return ret;
}
 
Example 2
Source File: AbstractIntegerDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * For a random variable {@code X} whose values are distributed
 * according to this distribution, this method returns
 * {@code P(x0 < X < x1)}.
 *
 * @param x0 Inclusive lower bound.
 * @param x1 Inclusive upper bound.
 * @return the probability that a random variable with this distribution
 * will take a value between {@code x0} and {@code x1},
 * including the endpoints.
 * @throws MathException if the cumulative probability can not be
 * computed due to convergence or other numerical errors.
 * @throws NumberIsTooSmallException if {@code x1 > x0}.
 */
@Override
public double cumulativeProbability(double x0, double x1)
    throws MathException {
    if (x1 < x0) {
        throw new NumberIsTooSmallException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT,
                                            x1, x0, true);
    }
    if (FastMath.floor(x0) < x0) {
        return cumulativeProbability(((int) FastMath.floor(x0)) + 1,
           (int) FastMath.floor(x1)); // don't want to count mass below x0
    } else { // x0 is mathematical integer, so use as is
        return cumulativeProbability((int) FastMath.floor(x0),
            (int) FastMath.floor(x1));
    }
}
 
Example 3
Source File: AbstractIntegerDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * For a random variable {@code X} whose values are distributed
 * according to this distribution, this method returns
 * {@code P(x0 <= X <= x1)}.
 *
 * @param x0 Inclusive lower bound.
 * @param x1 Inclusive upper bound.
 * @return the probability that a random variable with this distribution
 * will take a value between {@code x0} and {@code x1},
 * including the endpoints.
 * @throws MathException if the cumulative probability can not be
 * computed due to convergence or other numerical errors.
 * @throws NumberIsTooSmallException if {@code x1 > x0}.
 */
@Override
public double cumulativeProbability(double x0, double x1)
    throws MathException {
    if (x1 < x0) {
        throw new NumberIsTooSmallException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT,
                                            x1, x0, true);
    }
    if (FastMath.floor(x0) < x0) {
        return cumulativeProbability(((int) FastMath.floor(x0)) + 1,
           (int) FastMath.floor(x1)); // don't want to count mass below x0
    } else { // x0 is mathematical integer, so use as is
        return cumulativeProbability((int) FastMath.floor(x0),
            (int) FastMath.floor(x1));
    }
}
 
Example 4
Source File: AbstractIntegerDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * For a random variable X whose values are distributed according
 * to this distribution, this method returns P(x0 &le; X &le; x1).
 *
 * @param x0 the (inclusive) lower bound
 * @param x1 the (inclusive) upper bound
 * @return the probability that a random variable with this distribution
 * will take a value between <code>x0</code> and <code>x1</code>,
 * including the endpoints.
 * @throws MathException if the cumulative probability can not be
 * computed due to convergence or other numerical errors.
 * @throws IllegalArgumentException if <code>x0 > x1</code>
 */
@Override
public double cumulativeProbability(double x0, double x1)
    throws MathException {
    if (x0 > x1) {
        throw MathRuntimeException.createIllegalArgumentException(
              LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT, x0, x1);
    }
    if (FastMath.floor(x0) < x0) {
        return cumulativeProbability(((int) FastMath.floor(x0)) + 1,
           (int) FastMath.floor(x1)); // don't want to count mass below x0
    } else { // x0 is mathematical integer, so use as is
        return cumulativeProbability((int) FastMath.floor(x0),
            (int) FastMath.floor(x1));
    }
}
 
Example 5
Source File: PolynomialsUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Get the coefficients array for a given degree.
 * @param degree degree of the polynomial
 * @param coefficients list where the computed coefficients are stored
 * @param generator recurrence coefficients generator
 * @return coefficients array
 */
private static PolynomialFunction buildPolynomial(final int degree,
                                                  final ArrayList<BigFraction> coefficients,
                                                  final RecurrenceCoefficientsGenerator generator) {

    final int maxDegree = (int) FastMath.floor(FastMath.sqrt(2 * coefficients.size())) - 1;
    synchronized (PolynomialsUtils.class) {
        if (degree > maxDegree) {
            computeUpToDegree(degree, maxDegree, generator, coefficients);
        }
    }

    // coefficient  for polynomial 0 is  l [0]
    // coefficients for polynomial 1 are l [1] ... l [2] (degrees 0 ... 1)
    // coefficients for polynomial 2 are l [3] ... l [5] (degrees 0 ... 2)
    // coefficients for polynomial 3 are l [6] ... l [9] (degrees 0 ... 3)
    // coefficients for polynomial 4 are l[10] ... l[14] (degrees 0 ... 4)
    // coefficients for polynomial 5 are l[15] ... l[20] (degrees 0 ... 5)
    // coefficients for polynomial 6 are l[21] ... l[27] (degrees 0 ... 6)
    // ...
    final int start = degree * (degree + 1) / 2;

    final double[] a = new double[degree + 1];
    for (int i = 0; i <= degree; ++i) {
        a[i] = coefficients.get(start + i).doubleValue();
    }

    // build the polynomial
    return new PolynomialFunction(a);

}
 
Example 6
Source File: PolynomialsUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Get the coefficients array for a given degree.
 * @param degree degree of the polynomial
 * @param coefficients list where the computed coefficients are stored
 * @param generator recurrence coefficients generator
 * @return coefficients array
 */
private static PolynomialFunction buildPolynomial(final int degree,
                                                  final ArrayList<BigFraction> coefficients,
                                                  final RecurrenceCoefficientsGenerator generator) {

    final int maxDegree = (int) FastMath.floor(FastMath.sqrt(2 * coefficients.size())) - 1;
    synchronized (PolynomialsUtils.class) {
        if (degree > maxDegree) {
            computeUpToDegree(degree, maxDegree, generator, coefficients);
        }
    }

    // coefficient  for polynomial 0 is  l [0]
    // coefficients for polynomial 1 are l [1] ... l [2] (degrees 0 ... 1)
    // coefficients for polynomial 2 are l [3] ... l [5] (degrees 0 ... 2)
    // coefficients for polynomial 3 are l [6] ... l [9] (degrees 0 ... 3)
    // coefficients for polynomial 4 are l[10] ... l[14] (degrees 0 ... 4)
    // coefficients for polynomial 5 are l[15] ... l[20] (degrees 0 ... 5)
    // coefficients for polynomial 6 are l[21] ... l[27] (degrees 0 ... 6)
    // ...
    final int start = degree * (degree + 1) / 2;

    final double[] a = new double[degree + 1];
    for (int i = 0; i <= degree; ++i) {
        a[i] = coefficients.get(start + i).doubleValue();
    }

    // build the polynomial
    return new PolynomialFunction(a);

}
 
Example 7
Source File: Percentile.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns an estimate of the <code>p</code>th percentile of the values
 * in the <code>values</code> array, starting with the element in (0-based)
 * position <code>begin</code> in the array and including <code>length</code>
 * values.
 * <p>
 * Calls to this method do not modify the internal <code>quantile</code>
 * state of this statistic.</p>
 * <p>
 * <ul>
 * <li>Returns <code>Double.NaN</code> if <code>length = 0</code></li>
 * <li>Returns (for any value of <code>p</code>) <code>values[begin]</code>
 *  if <code>length = 1 </code></li>
 * <li>Throws <code>IllegalArgumentException</code> if <code>values</code>
 *  is null , <code>begin</code> or <code>length</code> is invalid, or
 * <code>p</code> is not a valid quantile value (p must be greater than 0
 * and less than or equal to 100)</li>
 * </ul></p>
 * <p>
 * See {@link Percentile} for a description of the percentile estimation
 * algorithm used.</p>
 *
 * @param values array of input values
 * @param p  the percentile to compute
 * @param begin  the first (0-based) element to include in the computation
 * @param length  the number of array elements to include
 * @return  the percentile value
 * @throws IllegalArgumentException if the parameters are not valid or the
 * input array is null
 */
public double evaluate(final double[] values, final int begin,
        final int length, final double p) {

    test(values, begin, length);

    if ((p > 100) || (p <= 0)) {
        throw MathRuntimeException.createIllegalArgumentException(
              LocalizedFormats.OUT_OF_BOUNDS_QUANTILE_VALUE, p);
    }
    if (length == 0) {
        return Double.NaN;
    }
    if (length == 1) {
        return values[begin]; // always return single value for n = 1
    }
    double n = length;
    double pos = p * (n + 1) / 100;
    double fpos = FastMath.floor(pos);
    int intPos = (int) fpos;
    double dif = pos - fpos;
    double[] sorted = new double[length];
    System.arraycopy(values, begin, sorted, 0, length);
    Arrays.sort(sorted);

    if (pos < 1) {
        return sorted[0];
    }
    if (pos >= n) {
        return sorted[length - 1];
    }
    double lower = sorted[intPos - 1];
    double upper = sorted[intPos];
    return lower + dif * (upper - lower);
}
 
Example 8
Source File: PolynomialsUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Get the coefficients array for a given degree.
 * @param degree degree of the polynomial
 * @param coefficients list where the computed coefficients are stored
 * @param generator recurrence coefficients generator
 * @return coefficients array
 */
private static PolynomialFunction buildPolynomial(final int degree,
                                                  final ArrayList<BigFraction> coefficients,
                                                  final RecurrenceCoefficientsGenerator generator) {

    final int maxDegree = (int) FastMath.floor(FastMath.sqrt(2 * coefficients.size())) - 1;
    synchronized (PolynomialsUtils.class) {
        if (degree > maxDegree) {
            computeUpToDegree(degree, maxDegree, generator, coefficients);
        }
    }

    // coefficient  for polynomial 0 is  l [0]
    // coefficients for polynomial 1 are l [1] ... l [2] (degrees 0 ... 1)
    // coefficients for polynomial 2 are l [3] ... l [5] (degrees 0 ... 2)
    // coefficients for polynomial 3 are l [6] ... l [9] (degrees 0 ... 3)
    // coefficients for polynomial 4 are l[10] ... l[14] (degrees 0 ... 4)
    // coefficients for polynomial 5 are l[15] ... l[20] (degrees 0 ... 5)
    // coefficients for polynomial 6 are l[21] ... l[27] (degrees 0 ... 6)
    // ...
    final int start = degree * (degree + 1) / 2;

    final double[] a = new double[degree + 1];
    for (int i = 0; i <= degree; ++i) {
        a[i] = coefficients.get(start + i).doubleValue();
    }

    // build the polynomial
    return new PolynomialFunction(a);

}
 
Example 9
Source File: Floor.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public double value(double x) {
    return FastMath.floor(x);
}
 
Example 10
Source File: ComposableFunction.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public double value(double d) {
    return FastMath.floor(d);
}
 
Example 11
Source File: Fraction.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create a fraction given the double value and either the maximum error
 * allowed or the maximum number of denominator digits.
 * <p>
 *
 * NOTE: This constructor is called with EITHER
 *   - a valid epsilon value and the maxDenominator set to Integer.MAX_VALUE
 *     (that way the maxDenominator has no effect).
 * OR
 *   - a valid maxDenominator value and the epsilon value set to zero
 *     (that way epsilon only has effect if there is an exact match before
 *     the maxDenominator value is reached).
 * </p><p>
 *
 * It has been done this way so that the same code can be (re)used for both
 * scenarios. However this could be confusing to users if it were part of
 * the public API and this constructor should therefore remain PRIVATE.
 * </p>
 *
 * See JIRA issue ticket MATH-181 for more details:
 *
 *     https://issues.apache.org/jira/browse/MATH-181
 *
 * @param value the double value to convert to a fraction.
 * @param epsilon maximum error allowed.  The resulting fraction is within
 *        {@code epsilon} of {@code value}, in absolute terms.
 * @param maxDenominator maximum denominator value allowed.
 * @param maxIterations maximum number of convergents
 * @throws FractionConversionException if the continued fraction failed to
 *         converge.
 */
private Fraction(double value, double epsilon, int maxDenominator, int maxIterations)
    throws FractionConversionException
{
    long overflow = Integer.MAX_VALUE;
    double r0 = value;
    long a0 = (long)FastMath.floor(r0);
    if (a0 > overflow) {
        throw new FractionConversionException(value, a0, 1l);
    }

    // check for (almost) integer arguments, which should not go
    // to iterations.
    if (FastMath.abs(a0 - value) < epsilon) {
        this.numerator = (int) a0;
        this.denominator = 1;
        return;
    }

    long p0 = 1;
    long q0 = 0;
    long p1 = a0;
    long q1 = 1;

    long p2 = 0;
    long q2 = 1;

    int n = 0;
    boolean stop = false;
    do {
        ++n;
        double r1 = 1.0 / (r0 - a0);
        long a1 = (long)FastMath.floor(r1);
        p2 = (a1 * p1) + p0;
        q2 = (a1 * q1) + q0;
        if ((p2 > overflow) || (q2 > overflow)) {
            throw new FractionConversionException(value, p2, q2);
        }

        double convergent = (double)p2 / (double)q2;
        if (n < maxIterations && FastMath.abs(convergent - value) > epsilon && q2 < maxDenominator) {
            p0 = p1;
            p1 = p2;
            q0 = q1;
            q1 = q2;
            a0 = a1;
            r0 = r1;
        } else {
            stop = true;
        }
    } while (!stop);

    if (n >= maxIterations) {
        throw new FractionConversionException(value, maxIterations);
    }

    if (q2 < maxDenominator) {
        this.numerator = (int) p2;
        this.denominator = (int) q2;
    } else {
        this.numerator = (int) p1;
        this.denominator = (int) q1;
    }

}
 
Example 12
Source File: BigFraction.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create a fraction given the double value and either the maximum error
 * allowed or the maximum number of denominator digits.
 * <p>
 *
 * NOTE: This constructor is called with EITHER - a valid epsilon value and
 * the maxDenominator set to Integer.MAX_VALUE (that way the maxDenominator
 * has no effect). OR - a valid maxDenominator value and the epsilon value
 * set to zero (that way epsilon only has effect if there is an exact match
 * before the maxDenominator value is reached).
 * </p>
 * <p>
 *
 * It has been done this way so that the same code can be (re)used for both
 * scenarios. However this could be confusing to users if it were part of
 * the public API and this constructor should therefore remain PRIVATE.
 * </p>
 *
 * See JIRA issue ticket MATH-181 for more details:
 *
 * https://issues.apache.org/jira/browse/MATH-181
 *
 * @param value
 *            the double value to convert to a fraction.
 * @param epsilon
 *            maximum error allowed. The resulting fraction is within
 *            <code>epsilon</code> of <code>value</code>, in absolute terms.
 * @param maxDenominator
 *            maximum denominator value allowed.
 * @param maxIterations
 *            maximum number of convergents.
 * @throws FractionConversionException
 *             if the continued fraction failed to converge.
 */
private BigFraction(final double value, final double epsilon,
                    final int maxDenominator, int maxIterations)
    throws FractionConversionException {
    long overflow = Integer.MAX_VALUE;
    double r0 = value;
    long a0 = (long) FastMath.floor(r0);
    if (a0 > overflow) {
        throw new FractionConversionException(value, a0, 1l);
    }

    // check for (almost) integer arguments, which should not go
    // to iterations.
    if (FastMath.abs(a0 - value) < epsilon) {
        numerator = BigInteger.valueOf(a0);
        denominator = BigInteger.ONE;
        return;
    }

    long p0 = 1;
    long q0 = 0;
    long p1 = a0;
    long q1 = 1;

    long p2 = 0;
    long q2 = 1;

    int n = 0;
    boolean stop = false;
    do {
        ++n;
        final double r1 = 1.0 / (r0 - a0);
        final long a1 = (long) FastMath.floor(r1);
        p2 = (a1 * p1) + p0;
        q2 = (a1 * q1) + q0;
        if ((p2 > overflow) || (q2 > overflow)) {
            throw new FractionConversionException(value, p2, q2);
        }

        final double convergent = (double) p2 / (double) q2;
        if ((n < maxIterations) &&
            (FastMath.abs(convergent - value) > epsilon) &&
            (q2 < maxDenominator)) {
            p0 = p1;
            p1 = p2;
            q0 = q1;
            q1 = q2;
            a0 = a1;
            r0 = r1;
        } else {
            stop = true;
        }
    } while (!stop);

    if (n >= maxIterations) {
        throw new FractionConversionException(value, maxIterations);
    }

    if (q2 < maxDenominator) {
        numerator   = BigInteger.valueOf(p2);
        denominator = BigInteger.valueOf(q2);
    } else {
        numerator   = BigInteger.valueOf(p1);
        denominator = BigInteger.valueOf(q1);
    }
}
 
Example 13
Source File: Floor.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public double value(double x) {
    return FastMath.floor(x);
}
 
Example 14
Source File: Percentile.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns an estimate of the <code>p</code>th percentile of the values
 * in the <code>values</code> array, starting with the element in (0-based)
 * position <code>begin</code> in the array and including <code>length</code>
 * values.
 * <p>
 * Calls to this method do not modify the internal <code>quantile</code>
 * state of this statistic.</p>
 * <p>
 * <ul>
 * <li>Returns <code>Double.NaN</code> if <code>length = 0</code></li>
 * <li>Returns (for any value of <code>p</code>) <code>values[begin]</code>
 *  if <code>length = 1 </code></li>
 * <li>Throws <code>IllegalArgumentException</code> if <code>values</code>
 *  is null , <code>begin</code> or <code>length</code> is invalid, or
 * <code>p</code> is not a valid quantile value (p must be greater than 0
 * and less than or equal to 100)</li>
 * </ul></p>
 * <p>
 * See {@link Percentile} for a description of the percentile estimation
 * algorithm used.</p>
 *
 * @param values array of input values
 * @param p  the percentile to compute
 * @param begin  the first (0-based) element to include in the computation
 * @param length  the number of array elements to include
 * @return  the percentile value
 * @throws IllegalArgumentException if the parameters are not valid or the
 * input array is null
 */
public double evaluate(final double[] values, final int begin,
        final int length, final double p) {

    test(values, begin, length);

    if ((p > 100) || (p <= 0)) {
        throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUNDS_QUANTILE_VALUE, p, 0, 100);
    }
    if (length == 0) {
        return Double.NaN;
    }
    if (length == 1) {
        return values[begin]; // always return single value for n = 1
    }
    double n = length;
    double pos = p * (n + 1) / 100;
    double fpos = FastMath.floor(pos);
    int intPos = (int) fpos;
    double dif = pos - fpos;
    double[] work;
    int[] pivotsHeap;
    if (values == getDataRef()) {
        work = getDataRef();
        pivotsHeap = cachedPivots;
    } else {
        work = new double[length];
        System.arraycopy(values, begin, work, 0, length);
        pivotsHeap = new int[(0x1 << MAX_CACHED_LEVELS) - 1];
        Arrays.fill(pivotsHeap, -1);
    }

    if (pos < 1) {
        return select(work, pivotsHeap, 0);
    }
    if (pos >= n) {
        return select(work, pivotsHeap, length - 1);
    }
    double lower = select(work, pivotsHeap, intPos - 1);
    double upper = select(work, pivotsHeap, intPos);
    return lower + dif * (upper - lower);
}
 
Example 15
Source File: Floor.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public double value(double x) {
    return FastMath.floor(x);
}
 
Example 16
Source File: Percentile.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns an estimate of the <code>p</code>th percentile of the values
 * in the <code>values</code> array, starting with the element in (0-based)
 * position <code>begin</code> in the array and including <code>length</code>
 * values.
 * <p>
 * Calls to this method do not modify the internal <code>quantile</code>
 * state of this statistic.</p>
 * <p>
 * <ul>
 * <li>Returns <code>Double.NaN</code> if <code>length = 0</code></li>
 * <li>Returns (for any value of <code>p</code>) <code>values[begin]</code>
 *  if <code>length = 1 </code></li>
 * <li>Throws <code>IllegalArgumentException</code> if <code>values</code>
 *  is null , <code>begin</code> or <code>length</code> is invalid, or
 * <code>p</code> is not a valid quantile value (p must be greater than 0
 * and less than or equal to 100)</li>
 * </ul></p>
 * <p>
 * See {@link Percentile} for a description of the percentile estimation
 * algorithm used.</p>
 *
 * @param values array of input values
 * @param p  the percentile to compute
 * @param begin  the first (0-based) element to include in the computation
 * @param length  the number of array elements to include
 * @return  the percentile value
 * @throws IllegalArgumentException if the parameters are not valid or the
 * input array is null
 */
public double evaluate(final double[] values, final int begin,
        final int length, final double p) {

    test(values, begin, length);

    if ((p > 100) || (p <= 0)) {
        throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUNDS_QUANTILE_VALUE, p, 0, 100);
    }
    if (length == 0) {
        return Double.NaN;
    }
    if (length == 1) {
        return values[begin]; // always return single value for n = 1
    }
    double n = length;
    double pos = p * (n + 1) / 100;
    double fpos = FastMath.floor(pos);
    int intPos = (int) fpos;
    double dif = pos - fpos;
    double[] work;
    int[] pivotsHeap;
    if (values == getDataRef()) {
        work = getDataRef();
        pivotsHeap = cachedPivots;
    } else {
        work = new double[length];
        System.arraycopy(values, begin, work, 0, length);
        pivotsHeap = new int[(0x1 << MAX_CACHED_LEVELS) - 1];
        Arrays.fill(pivotsHeap, -1);
    }

    if (pos < 1) {
        return select(work, pivotsHeap, 0);
    }
    if (pos >= n) {
        return select(work, pivotsHeap, length - 1);
    }
    double lower = select(work, pivotsHeap, intPos - 1);
    double upper = select(work, pivotsHeap, intPos);
    return lower + dif * (upper - lower);
}
 
Example 17
Source File: Fraction.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create a fraction given the double value and either the maximum error
 * allowed or the maximum number of denominator digits.
 * <p>
 *
 * NOTE: This constructor is called with EITHER
 *   - a valid epsilon value and the maxDenominator set to Integer.MAX_VALUE
 *     (that way the maxDenominator has no effect).
 * OR
 *   - a valid maxDenominator value and the epsilon value set to zero
 *     (that way epsilon only has effect if there is an exact match before
 *     the maxDenominator value is reached).
 * </p><p>
 *
 * It has been done this way so that the same code can be (re)used for both
 * scenarios. However this could be confusing to users if it were part of
 * the public API and this constructor should therefore remain PRIVATE.
 * </p>
 *
 * See JIRA issue ticket MATH-181 for more details:
 *
 *     https://issues.apache.org/jira/browse/MATH-181
 *
 * @param value the double value to convert to a fraction.
 * @param epsilon maximum error allowed.  The resulting fraction is within
 *        {@code epsilon} of {@code value}, in absolute terms.
 * @param maxDenominator maximum denominator value allowed.
 * @param maxIterations maximum number of convergents
 * @throws FractionConversionException if the continued fraction failed to
 *         converge.
 */
private Fraction(double value, double epsilon, int maxDenominator, int maxIterations)
    throws FractionConversionException
{
    long overflow = Integer.MAX_VALUE;
    double r0 = value;
    long a0 = (long)FastMath.floor(r0);
    if (a0 > overflow) {
        throw new FractionConversionException(value, a0, 1l);
    }

    // check for (almost) integer arguments, which should not go
    // to iterations.
    if (FastMath.abs(a0 - value) < epsilon) {
        this.numerator = (int) a0;
        this.denominator = 1;
        return;
    }

    long p0 = 1;
    long q0 = 0;
    long p1 = a0;
    long q1 = 1;

    long p2 = 0;
    long q2 = 1;

    int n = 0;
    boolean stop = false;
    do {
        ++n;
        double r1 = 1.0 / (r0 - a0);
        long a1 = (long)FastMath.floor(r1);
        p2 = (a1 * p1) + p0;
        q2 = (a1 * q1) + q0;
        if ((p2 > overflow) || (q2 > overflow)) {
            throw new FractionConversionException(value, p2, q2);
        }

        double convergent = (double)p2 / (double)q2;
        if (n < maxIterations && FastMath.abs(convergent - value) > epsilon && q2 < maxDenominator) {
            p0 = p1;
            p1 = p2;
            q0 = q1;
            q1 = q2;
            a0 = a1;
            r0 = r1;
        } else {
            stop = true;
        }
    } while (!stop);

    if (n >= maxIterations) {
        throw new FractionConversionException(value, maxIterations);
    }

    if (q2 < maxDenominator) {
        this.numerator = (int) p2;
        this.denominator = (int) q2;
    } else {
        this.numerator = (int) p1;
        this.denominator = (int) q1;
    }

}
 
Example 18
Source File: Math_36_BigFraction_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Create a fraction given the double value and either the maximum error
 * allowed or the maximum number of denominator digits.
 * <p>
 *
 * NOTE: This constructor is called with EITHER - a valid epsilon value and
 * the maxDenominator set to Integer.MAX_VALUE (that way the maxDenominator
 * has no effect). OR - a valid maxDenominator value and the epsilon value
 * set to zero (that way epsilon only has effect if there is an exact match
 * before the maxDenominator value is reached).
 * </p>
 * <p>
 *
 * It has been done this way so that the same code can be (re)used for both
 * scenarios. However this could be confusing to users if it were part of
 * the public API and this constructor should therefore remain PRIVATE.
 * </p>
 *
 * See JIRA issue ticket MATH-181 for more details:
 *
 * https://issues.apache.org/jira/browse/MATH-181
 *
 * @param value
 *            the double value to convert to a fraction.
 * @param epsilon
 *            maximum error allowed. The resulting fraction is within
 *            <code>epsilon</code> of <code>value</code>, in absolute terms.
 * @param maxDenominator
 *            maximum denominator value allowed.
 * @param maxIterations
 *            maximum number of convergents.
 * @throws FractionConversionException
 *             if the continued fraction failed to converge.
 */
private BigFraction(final double value, final double epsilon,
                    final int maxDenominator, int maxIterations)
    throws FractionConversionException {
    long overflow = Integer.MAX_VALUE;
    double r0 = value;
    long a0 = (long) FastMath.floor(r0);
    if (a0 > overflow) {
        throw new FractionConversionException(value, a0, 1l);
    }

    // check for (almost) integer arguments, which should not go
    // to iterations.
    if (FastMath.abs(a0 - value) < epsilon) {
        numerator = BigInteger.valueOf(a0);
        denominator = BigInteger.ONE;
        return;
    }

    long p0 = 1;
    long q0 = 0;
    long p1 = a0;
    long q1 = 1;

    long p2 = 0;
    long q2 = 1;

    int n = 0;
    boolean stop = false;
    do {
        ++n;
        final double r1 = 1.0 / (r0 - a0);
        final long a1 = (long) FastMath.floor(r1);
        p2 = (a1 * p1) + p0;
        q2 = (a1 * q1) + q0;
        if ((p2 > overflow) || (q2 > overflow)) {
            throw new FractionConversionException(value, p2, q2);
        }

        final double convergent = (double) p2 / (double) q2;
        if ((n < maxIterations) &&
            (FastMath.abs(convergent - value) > epsilon) &&
            (q2 < maxDenominator)) {
            p0 = p1;
            p1 = p2;
            q0 = q1;
            q1 = q2;
            a0 = a1;
            r0 = r1;
        } else {
            stop = true;
        }
    } while (!stop);

    if (n >= maxIterations) {
        throw new FractionConversionException(value, maxIterations);
    }

    if (q2 < maxDenominator) {
        numerator   = BigInteger.valueOf(p2);
        denominator = BigInteger.valueOf(q2);
    } else {
        numerator   = BigInteger.valueOf(p1);
        denominator = BigInteger.valueOf(q1);
    }
}
 
Example 19
Source File: AbstractIntegerDistribution.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * For a random variable X whose values are distributed according
 * to this distribution, this method returns P(X = x). In other words, this
 * method represents the probability mass function,  or PMF, for the distribution.
 * <p>
 * If <code>x</code> does not represent an integer value, 0 is returned.
 *
 * @param x the value at which the probability density function is evaluated
 * @return the value of the probability density function at x
 */
public double probability(double x) {
    double fl = FastMath.floor(x);
    if (fl == x) {
        return this.probability((int) x);
    } else {
        return 0;
    }
}
 
Example 20
Source File: AbstractIntegerDistribution.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * For a random variable {@code X} whose values are distributed according
 * to this distribution, this method returns {@code P(X = x)}. In other
 * words, this method represents the probability mass function, or PMF,
 * for the distribution.
 * If {@code x} does not represent an integer value, 0 is returned.
 *
 * @param x Value at which the probability density function is evaluated.
 * @return the value of the probability density function at {@code x}.
 */
public double probability(double x) {
    double fl = FastMath.floor(x);
    if (fl == x) {
        return this.probability((int) x);
    } else {
        return 0;
    }
}