Java Code Examples for org.apache.commons.math3.util.FastMath#round()

The following examples show how to use org.apache.commons.math3.util.FastMath#round() . 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: PSquarePercentileTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies that copied statistics remain equal to originals when
 * incremented the same way by way of copying original after just a few
 * elements are incremented
 */
@Test
public void testCopyConsistencyWithInitialFirstFewElements() {

    StorelessUnivariateStatistic master =
            (StorelessUnivariateStatistic) getUnivariateStatistic();

    StorelessUnivariateStatistic replica = null;

    // select a portion of testArray which is 10% of the length to load
    // first
    long index = FastMath.round(0.1 * testArray.length);

    // Put first half in master and copy master to replica
    master.incrementAll(testArray, 0, (int) index);
    replica = master.copy();

    // Check same
    Assert.assertTrue(replica.equals(master));
    Assert.assertTrue(master.equals(replica));
    // Now add second part to both and check again
    master.incrementAll(testArray, (int) index,
            (int) (testArray.length - index));
    replica.incrementAll(testArray, (int) index,
            (int) (testArray.length - index));
    Assert.assertTrue(master.equals(master));
    Assert.assertTrue(replica.equals(replica));
    Assert.assertTrue(replica.equals(master));
    Assert.assertTrue(master.equals(replica));
}
 
Example 2
Source File: StorelessUnivariateStatisticAbstractTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies that copied statistics remain equal to originals when
 * incremented the same way.
 *
 */
@Test
public void testCopyConsistency() {

    StorelessUnivariateStatistic master =
        (StorelessUnivariateStatistic) getUnivariateStatistic();

    StorelessUnivariateStatistic replica = null;

    // Randomly select a portion of testArray to load first
    long index = FastMath.round((FastMath.random()) * testArray.length);

    // Put first half in master and copy master to replica
    master.incrementAll(testArray, 0, (int) index);
    replica = master.copy();

    // Check same
    Assert.assertTrue(replica.equals(master));
    Assert.assertTrue(master.equals(replica));

    // Now add second part to both and check again
    master.incrementAll(testArray,
            (int) index, (int) (testArray.length - index));
    replica.incrementAll(testArray,
            (int) index, (int) (testArray.length - index));
    Assert.assertTrue(replica.equals(master));
    Assert.assertTrue(master.equals(replica));
}
 
Example 3
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Resolve a sequence of ties, using the configured {@link TiesStrategy}.
 * The input <code>ranks</code> array is expected to take the same value
 * for all indices in <code>tiesTrace</code>.  The common value is recoded
 * according to the tiesStrategy. For example, if ranks = <5,8,2,6,2,7,1,2>,
 * tiesTrace = <2,4,7> and tiesStrategy is MINIMUM, ranks will be unchanged.
 * The same array and trace with tiesStrategy AVERAGE will come out
 * <5,8,3,6,3,7,1,3>.
 *
 * @param ranks array of ranks
 * @param tiesTrace list of indices where <code>ranks</code> is constant
 * -- that is, for any i and j in TiesTrace, <code> ranks[i] == ranks[j]
 * </code>
 */
private void resolveTie(double[] ranks, List<Integer> tiesTrace) {

    // constant value of ranks over tiesTrace
    final double c = ranks[tiesTrace.get(0)];

    // length of sequence of tied ranks
    final int length = tiesTrace.size();

    switch (tiesStrategy) {
        case  AVERAGE:  // Replace ranks with average
            fill(ranks, tiesTrace, (2 * c + length - 1) / 2d);
            break;
        case MAXIMUM:   // Replace ranks with maximum values
            fill(ranks, tiesTrace, c + length - 1);
            break;
        case MINIMUM:   // Replace ties with minimum
            fill(ranks, tiesTrace, c);
            break;
        case RANDOM:    // Fill with random integral values in [c, c + length - 1]
            Iterator<Integer> iterator = tiesTrace.iterator();
            long f = FastMath.round(c);
            while (iterator.hasNext()) {
                ranks[iterator.next()] =
                    randomData.nextLong(f, f + length - 1);
            }
            break;
        case SEQUENTIAL:  // Fill sequentially from c to c + length - 1
            // walk and fill
            iterator = tiesTrace.iterator();
            f = FastMath.round(c);
            int i = 0;
            while (iterator.hasNext()) {
                ranks[iterator.next()] = f + i++;
            }
            break;
        default: // this should not happen unless TiesStrategy enum is changed
            throw new MathInternalError();
    }
}
 
Example 4
Source File: StorelessUnivariateStatisticAbstractTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies that copied statistics remain equal to originals when
 * incremented the same way.
 *
 */
@Test
public void testCopyConsistency() {

    StorelessUnivariateStatistic master =
        (StorelessUnivariateStatistic) getUnivariateStatistic();

    StorelessUnivariateStatistic replica = null;

    // Randomly select a portion of testArray to load first
    long index = FastMath.round((FastMath.random()) * testArray.length);

    // Put first half in master and copy master to replica
    master.incrementAll(testArray, 0, (int) index);
    replica = master.copy();

    // Check same
    Assert.assertTrue(replica.equals(master));
    Assert.assertTrue(master.equals(replica));

    // Now add second part to both and check again
    master.incrementAll(testArray,
            (int) index, (int) (testArray.length - index));
    replica.incrementAll(testArray,
            (int) index, (int) (testArray.length - index));
    Assert.assertTrue(replica.equals(master));
    Assert.assertTrue(master.equals(replica));
}
 
Example 5
Source File: ParameterRange.java    From myrrix-recommender with Apache License 2.0 5 votes vote down vote up
/**
 * @param numSteps must be at least 2. The number of value steps to construct
 * @return value steps to try for this parameter value. {@code min} and {@code max} are the first and last
 *  elements. The values are not necessarily distributed uniformly in the range.
 */
public Number[] buildSteps(int numSteps) {
  Preconditions.checkArgument(numSteps >= 2, "numSteps must be at least 2: {}", numSteps);
  if (min == max) {
    return new Number[] { maybeRound(min) };
  }
  if (integerOnly) {
    int roundedMin = (int) FastMath.round(min);
    int roundedMax = (int) FastMath.round(max);
    int maxResonableSteps = roundedMax - roundedMin + 1;
    if (numSteps >= maxResonableSteps) {
      Number[] sequence = new Number[maxResonableSteps];
      for (int i = 0; i < sequence.length; i++) {
        sequence[i] = roundedMin + i;
      }
      return sequence;
    }
  }

  Number[] stepValues = new Number[numSteps];
  stepValues[0] = maybeRound(min);
  stepValues[stepValues.length - 1] = maybeRound(max);
  double range = max - min;
  for (int i = 1; i < stepValues.length - 1; i++) {
    double fraction = (double) i / (numSteps-1);
    stepValues[i] = maybeRound(min + range * fraction * fraction);
  }
  return stepValues;
}
 
Example 6
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Resolve a sequence of ties, using the configured {@link TiesStrategy}.
 * The input <code>ranks</code> array is expected to take the same value
 * for all indices in <code>tiesTrace</code>.  The common value is recoded
 * according to the tiesStrategy. For example, if ranks = <5,8,2,6,2,7,1,2>,
 * tiesTrace = <2,4,7> and tiesStrategy is MINIMUM, ranks will be unchanged.
 * The same array and trace with tiesStrategy AVERAGE will come out
 * <5,8,3,6,3,7,1,3>.
 *
 * @param ranks array of ranks
 * @param tiesTrace list of indices where <code>ranks</code> is constant
 * -- that is, for any i and j in TiesTrace, <code> ranks[i] == ranks[j]
 * </code>
 */
private void resolveTie(double[] ranks, List<Integer> tiesTrace) {

    // constant value of ranks over tiesTrace
    final double c = ranks[tiesTrace.get(0)];

    // length of sequence of tied ranks
    final int length = tiesTrace.size();

    switch (tiesStrategy) {
        case  AVERAGE:  // Replace ranks with average
            fill(ranks, tiesTrace, (2 * c + length - 1) / 2d);
            break;
        case MAXIMUM:   // Replace ranks with maximum values
            fill(ranks, tiesTrace, c + length - 1);
            break;
        case MINIMUM:   // Replace ties with minimum
            fill(ranks, tiesTrace, c);
            break;
        case RANDOM:    // Fill with random integral values in [c, c + length - 1]
            Iterator<Integer> iterator = tiesTrace.iterator();
            long f = FastMath.round(c);
            while (iterator.hasNext()) {
                ranks[iterator.next()] =
                    randomData.nextLong(f, f + length - 1);
            }
            break;
        case SEQUENTIAL:  // Fill sequentially from c to c + length - 1
            // walk and fill
            iterator = tiesTrace.iterator();
            f = FastMath.round(c);
            int i = 0;
            while (iterator.hasNext()) {
                ranks[iterator.next()] = f + i++;
            }
            break;
        default: // this should not happen unless TiesStrategy enum is changed
            throw new MathInternalError();
    }
}
 
Example 7
Source File: EmpiricalDistributionTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find the bin that x belongs (relative to {@link #makeDistribution()}).
 */
private int findBin(double x) {
    // Number of bins below x should be trunc(x/10)
    final double nMinus = FastMath.floor(x / 10);
    final int bin =  (int) FastMath.round(nMinus);
    // If x falls on a bin boundary, it is in the lower bin
    return FastMath.floor(x / 10) == x / 10 ? bin - 1 : bin;
}
 
Example 8
Source File: DerivativeStructure.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public long round() {
    return FastMath.round(data[0]);
}
 
Example 9
Source File: CalculatedValue.java    From microMathematics with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Procedure rounds the given value to the given number of significant digits see
 * http://stackoverflow.com/questions/202302
 *
 * Note: The maximum double value in Java is on the order of 10^308, while the minimum value is on the order of
 * 10^-324. Therefore, you can run into trouble when applying the function roundToSignificantFigures to something
 * that's within a few powers of ten of Double.MIN_VALUE.
 *
 * Consequently, the variable magnitude may become Infinity, and it's all garbage from then on out. Fortunately,
 * this is not an insurmountable problem: it is only the factor magnitude that's overflowing. What really matters is
 * the product num * magnitude, and that does not overflow. One way of resolving this is by breaking up the
 * multiplication by the factor magintude into two steps.
 */
public static double roundToNumberOfSignificantDigits(double num, int n)
{
    if (num == 0)
    {
        return 0;
    }

    try
    {
        return new BigDecimal(num).round(new MathContext(n, RoundingMode.HALF_EVEN)).doubleValue();
    }
    catch (ArithmeticException ex)
    {
        // nothing to do
    }

    final double maxPowerOfTen = FastMath.floor(FastMath.log10(Double.MAX_VALUE));
    final double d = FastMath.ceil(FastMath.log10(num < 0 ? -num : num));
    final int power = n - (int) d;

    double firstMagnitudeFactor = 1.0;
    double secondMagnitudeFactor = 1.0;
    if (power > maxPowerOfTen)
    {
        firstMagnitudeFactor = FastMath.pow(10.0, maxPowerOfTen);
        secondMagnitudeFactor = FastMath.pow(10.0, (double) power - maxPowerOfTen);
    }
    else
    {
        firstMagnitudeFactor = FastMath.pow(10.0, (double) power);
    }

    double toBeRounded = num * firstMagnitudeFactor;
    toBeRounded *= secondMagnitudeFactor;

    final long shifted = FastMath.round(toBeRounded);
    double rounded = ((double) shifted) / firstMagnitudeFactor;
    rounded /= secondMagnitudeFactor;
    return rounded;
}
 
Example 10
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Resolve a sequence of ties, using the configured {@link TiesStrategy}.
 * The input <code>ranks</code> array is expected to take the same value
 * for all indices in <code>tiesTrace</code>.  The common value is recoded
 * according to the tiesStrategy. For example, if ranks = <5,8,2,6,2,7,1,2>,
 * tiesTrace = <2,4,7> and tiesStrategy is MINIMUM, ranks will be unchanged.
 * The same array and trace with tiesStrategy AVERAGE will come out
 * <5,8,3,6,3,7,1,3>.
 *
 * @param ranks array of ranks
 * @param tiesTrace list of indices where <code>ranks</code> is constant
 * -- that is, for any i and j in TiesTrace, <code> ranks[i] == ranks[j]
 * </code>
 */
private void resolveTie(double[] ranks, List<Integer> tiesTrace) {

    // constant value of ranks over tiesTrace
    final double c = ranks[tiesTrace.get(0)];

    // length of sequence of tied ranks
    final int length = tiesTrace.size();

    switch (tiesStrategy) {
        case  AVERAGE:  // Replace ranks with average
            fill(ranks, tiesTrace, (2 * c + length - 1) / 2d);
            break;
        case MAXIMUM:   // Replace ranks with maximum values
            fill(ranks, tiesTrace, c + length - 1);
            break;
        case MINIMUM:   // Replace ties with minimum
            fill(ranks, tiesTrace, c);
            break;
        case RANDOM:    // Fill with random integral values in [c, c + length - 1]
            Iterator<Integer> iterator = tiesTrace.iterator();
            long f = FastMath.round(c);
            while (iterator.hasNext()) {
                // No advertised exception because args are guaranteed valid
                ranks[iterator.next()] =
                    randomData.nextLong(f, f + length - 1);
            }
            break;
        case SEQUENTIAL:  // Fill sequentially from c to c + length - 1
            // walk and fill
            iterator = tiesTrace.iterator();
            f = FastMath.round(c);
            int i = 0;
            while (iterator.hasNext()) {
                ranks[iterator.next()] = f + i++;
            }
            break;
        default: // this should not happen unless TiesStrategy enum is changed
            throw new MathInternalError();
    }
}
 
Example 11
Source File: DerivativeStructure.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** Get the closest long to instance value.
 * @return closest long to {@link #getValue()}
 */
public long round() {
    return FastMath.round(data[0]);
}
 
Example 12
Source File: Dfp.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc}
 * @since 3.2
 */
public long round() {
    return FastMath.round(toDouble());
}
 
Example 13
Source File: Dfp.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc}
 * @since 3.2
 */
public long round() {
    return FastMath.round(toDouble());
}
 
Example 14
Source File: DerivativeStructure.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public long round() {
    return FastMath.round(data[0]);
}
 
Example 15
Source File: Dfp.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc}
 * @since 3.2
 */
public long round() {
    return FastMath.round(toDouble());
}
 
Example 16
Source File: SparseGradient.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public long round() {
    return FastMath.round(value);
}
 
Example 17
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Resolve a sequence of ties, using the configured {@link TiesStrategy}.
 * The input <code>ranks</code> array is expected to take the same value
 * for all indices in <code>tiesTrace</code>.  The common value is recoded
 * according to the tiesStrategy. For example, if ranks = <5,8,2,6,2,7,1,2>,
 * tiesTrace = <2,4,7> and tiesStrategy is MINIMUM, ranks will be unchanged.
 * The same array and trace with tiesStrategy AVERAGE will come out
 * <5,8,3,6,3,7,1,3>.
 *
 * @param ranks array of ranks
 * @param tiesTrace list of indices where <code>ranks</code> is constant
 * -- that is, for any i and j in TiesTrace, <code> ranks[i] == ranks[j]
 * </code>
 */
private void resolveTie(double[] ranks, List<Integer> tiesTrace) {

    // constant value of ranks over tiesTrace
    final double c = ranks[tiesTrace.get(0)];

    // length of sequence of tied ranks
    final int length = tiesTrace.size();

    switch (tiesStrategy) {
        case  AVERAGE:  // Replace ranks with average
            fill(ranks, tiesTrace, (2 * c + length - 1) / 2d);
            break;
        case MAXIMUM:   // Replace ranks with maximum values
            fill(ranks, tiesTrace, c + length - 1);
            break;
        case MINIMUM:   // Replace ties with minimum
            fill(ranks, tiesTrace, c);
            break;
        case RANDOM:    // Fill with random integral values in [c, c + length - 1]
            Iterator<Integer> iterator = tiesTrace.iterator();
            long f = FastMath.round(c);
            while (iterator.hasNext()) {
                // No advertised exception because args are guaranteed valid
                ranks[iterator.next()] =
                    randomData.nextLong(f, f + length - 1);
            }
            break;
        case SEQUENTIAL:  // Fill sequentially from c to c + length - 1
            // walk and fill
            iterator = tiesTrace.iterator();
            f = FastMath.round(c);
            int i = 0;
            while (iterator.hasNext()) {
                ranks[iterator.next()] = f + i++;
            }
            break;
        default: // this should not happen unless TiesStrategy enum is changed
            throw new MathInternalError();
    }
}
 
Example 18
Source File: Dfp.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc}
 * @since 3.2
 */
public long round() {
    return FastMath.round(toDouble());
}
 
Example 19
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Resolve a sequence of ties, using the configured {@link TiesStrategy}.
 * The input <code>ranks</code> array is expected to take the same value
 * for all indices in <code>tiesTrace</code>.  The common value is recoded
 * according to the tiesStrategy. For example, if ranks = <5,8,2,6,2,7,1,2>,
 * tiesTrace = <2,4,7> and tiesStrategy is MINIMUM, ranks will be unchanged.
 * The same array and trace with tiesStrategy AVERAGE will come out
 * <5,8,3,6,3,7,1,3>.
 *
 * @param ranks array of ranks
 * @param tiesTrace list of indices where <code>ranks</code> is constant
 * -- that is, for any i and j in TiesTrace, <code> ranks[i] == ranks[j]
 * </code>
 */
private void resolveTie(double[] ranks, List<Integer> tiesTrace) {

    // constant value of ranks over tiesTrace
    final double c = ranks[tiesTrace.get(0)];

    // length of sequence of tied ranks
    final int length = tiesTrace.size();

    switch (tiesStrategy) {
        case  AVERAGE:  // Replace ranks with average
            fill(ranks, tiesTrace, (2 * c + length - 1) / 2d);
            break;
        case MAXIMUM:   // Replace ranks with maximum values
            fill(ranks, tiesTrace, c + length - 1);
            break;
        case MINIMUM:   // Replace ties with minimum
            fill(ranks, tiesTrace, c);
            break;
        case RANDOM:    // Fill with random integral values in [c, c + length - 1]
            Iterator<Integer> iterator = tiesTrace.iterator();
            long f = FastMath.round(c);
            while (iterator.hasNext()) {
                // No advertised exception because args are guaranteed valid
                ranks[iterator.next()] =
                    randomData.nextLong(f, f + length - 1);
            }
            break;
        case SEQUENTIAL:  // Fill sequentially from c to c + length - 1
            // walk and fill
            iterator = tiesTrace.iterator();
            f = FastMath.round(c);
            int i = 0;
            while (iterator.hasNext()) {
                ranks[iterator.next()] = f + i++;
            }
            break;
        default: // this should not happen unless TiesStrategy enum is changed
            throw new MathInternalError();
    }
}
 
Example 20
Source File: MannWhitneyU.java    From gatk with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Creates histogram of test statistics from a permutation test.
 *
 * @param series1 Data from group 1
 * @param series2 Data from group 2
 * @param testStatU Test statistic U from observed data
 * @return P-value based on histogram with u calculated for every possible permutation of group tag.
 */
public double permutationTest(final double[] series1, final double[] series2, final double testStatU) {

    // note that Mann-Whitney U stats are always integer or half-integer (this is true even in the case of ties)
    // thus for safety we store a histogram of twice the Mann-Whitney values
    final Histogram<Long> histo = new Histogram<>();
    final int n1 = series1.length;
    final int n2 = series2.length;

    RankedData rankedGroups = calculateRank(series1, series2);
    Rank[] ranks = rankedGroups.getRank();

    Integer[] firstPermutation = new Integer[n1 + n2];

    for (int i = 0; i < firstPermutation.length; i++) {
        if (i < n1) {
            firstPermutation[i] = 0;
        } else {
            firstPermutation[i] = 1;
        }
    }

    final int numOfPerms = (int) MathUtils.binomialCoefficient(n1 + n2, n2);
    Set<List<Integer>> allPermutations = getPermutations(firstPermutation, numOfPerms);

    double[] newSeries1 = new double[n1];
    double[] newSeries2 = new double[n2];

    //iterate over all permutations
    for (List<Integer> currPerm : allPermutations) {
        int series1End = 0;
        int series2End = 0;
        for (int i = 0; i < currPerm.size(); i++) {
            int grouping = currPerm.get(i);
            if (grouping == 0) {
                newSeries1[series1End] = ranks[i].rank;
                series1End++;
            } else {
                newSeries2[series2End] = ranks[i].rank;
                series2End++;
            }
        }
        assert (series1End == n1);
        assert (series2End == n2);

        double newU = MathUtils.sum(newSeries1) - ((n1 * (n1 + 1)) / 2.0);
        histo.increment(FastMath.round(2 * newU));
    }

    /**
     * In order to deal with edge cases where the observed value is also the most extreme value, we are taking half
     * of the count in the observed bin plus everything more extreme (in the FIRST_DOMINATES case the smaller bins)
     * and dividing by the total count of everything in the histogram. Just using getCumulativeDistribution() gives
     * a p-value of 1 in the most extreme case which doesn't result in a usable z-score.
     */
    double sumOfAllSmallerBins = histo.get(FastMath.round(2 * testStatU)).getValue() / 2.0;

    for (final Histogram.Bin<Long> bin : histo.values()) {
        if (bin.getId() < FastMath.round(2 * testStatU)) sumOfAllSmallerBins += bin.getValue();
    }

    return sumOfAllSmallerBins / histo.getCount();
}