Example usage for org.apache.commons.math3.util ArithmeticUtils pow

List of usage examples for org.apache.commons.math3.util ArithmeticUtils pow

Introduction

In this page you can find the example usage for org.apache.commons.math3.util ArithmeticUtils pow.

Prototype

public static BigInteger pow(final BigInteger k, BigInteger e) throws NotPositiveException 

Source Link

Document

Raise a BigInteger to a BigInteger power.

Usage

From source file:beast.math.NumberFormatter.java

public void setSignificantFigures(int sf) {
    this.sf = sf;

    upperCutoff = ArithmeticUtils.pow(10, sf - 1);
    cutoffTable = LongStream.iterate(1, l -> 10 * l).limit(sf).asDoubleStream().toArray();

    decimalFormat.setMinimumIntegerDigits(1);
    decimalFormat.setMaximumFractionDigits(sf - 1);
    decimalFormat.setMinimumFractionDigits(sf - 1);

    scientificFormat = getScientificFormat();

    fieldWidth = sf;/* ww w.  ja  v  a  2s . co m*/
}

From source file:cc.redberry.core.number.Exponentiation.java

static BigInteger findIntegerRoot(BigInteger base, BigInteger power) {
    BigInteger maxBits = BigInteger.valueOf(base.bitLength() + 1); // base < 2 ^ (maxBits + 1)
    // => base ^ ( 1 / power ) < 2 ^ ( (maxBits + 1) / power )

    BigInteger[] divResult = maxBits.divideAndRemainder(power);
    if (divResult[1].signum() == 0) // i.e. divResult[1] == 0
        maxBits = divResult[0];/*from  w w  w .  ja  va 2 s. c o  m*/
    else
        maxBits = divResult[0].add(BigInteger.ONE);

    if (maxBits.bitLength() > 31)
        throw new RuntimeException("Too many bits...");

    int targetBitsNumber = maxBits.intValue();
    int resultLengthM1 = targetBitsNumber / 8 + 1; //resultLength minus one
    byte[] result = new byte[resultLengthM1];
    resultLengthM1--;

    int bitNumber = targetBitsNumber;

    int cValue;
    BigInteger testValue;

    while ((--bitNumber) >= 0) {
        //setting bit
        result[resultLengthM1 - (bitNumber >> 3)] |= 1 << (bitNumber & 0x7);

        //Testing
        testValue = new BigInteger(result);
        cValue = ArithmeticUtils.pow(testValue, power).compareTo(base);
        if (cValue == 0)
            return testValue;
        if (cValue > 0)
            result[resultLengthM1 - (bitNumber >> 3)] &= ~(1 << (bitNumber & 0x7));
    }

    return null;
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.algorithm.PAES.java

/**
 * Constructs a new PAES instance./*from   w  w  w .  j  a  v a  2  s.c om*/
 * 
 * @param problem the problem
 * @param variation the mutation operator
 * @param bisections the number of bisections in the adaptive grid archive
 * @param archiveSize the capacity of the adaptive grid archive
 * @throws IllegalArgumentExceptio if the variation operator requires more
 *         than one parent
 */
public PAES(Problem problem, Variation variation, int bisections, int archiveSize) {
    super(problem, new Population(),
            new AdaptiveGridArchive(archiveSize, problem, ArithmeticUtils.pow(2, bisections)), null);
    this.variation = variation;

    if (variation.getArity() != 1) {
        throw new IllegalArgumentException("PAES only supports mutation operators with 1 parent");
    }

    comparator = new ParetoDominanceComparator();
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.algorithm.PESA2.java

/**
 * Constructs a new PESA2 instance./* w  w  w  .j  a v a2  s . com*/
 * 
 * @param problem the problem
 * @param variation the mutation operator
 * @param initialization the initialization operator
 * @param bisections the number of bisections in the adaptive grid archive
 * @param archiveSize the capacity of the adaptive grid archive
 */
public PESA2(Problem problem, Variation variation, Initialization initialization, int bisections,
        int archiveSize) {
    super(problem, new Population(),
            new AdaptiveGridArchive(archiveSize, problem, ArithmeticUtils.pow(2, bisections)), initialization);
    this.variation = variation;

    selection = new RegionBasedSelection();
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.core.AdaptiveGridArchive.java

/**
 * Constructs an adaptive grid archive with the specified capacity with the
 * specified number of divisions along each objective.
 * // ww w. j  ava  2s  . c o  m
 * @param capacity the capacity of this archive
 * @param problem the problem for which this archive is used
 * @param numberOfDivisions the number of divisions this archive uses to
 *        split each objective
 */
public AdaptiveGridArchive(int capacity, Problem problem, int numberOfDivisions) {
    super(new ParetoDominanceComparator(), true);
    this.capacity = capacity;
    this.problem = problem;
    this.numberOfDivisions = numberOfDivisions;

    minimum = new double[problem.getNumberOfObjectives()];
    maximum = new double[problem.getNumberOfObjectives()];
    density = new int[ArithmeticUtils.pow(numberOfDivisions, problem.getNumberOfObjectives())];

    adaptGrid();
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.core.indicator.RIndicator.java

/**
 * Generates uniformly-distributed weights.
 * /*from www .j  av  a 2s . co m*/
 * @param s the number of subdivisions along each objective
 * @param k the number of objectives
 * @return the uniformly-distributed weights
 */
private static double[][] generateUniformWeights(int s, int k) {
    int counter = 0;
    int N = ArithmeticUtils.pow(s + 1, k);

    double[][] weights = new double[(int) CombinatoricsUtils.binomialCoefficient(s + k - 1, k - 1)][k];

    for (int i = 0; i < N; i++) {
        int sum = 0;
        int[] kary = toBaseK(i, s + 1, k);

        for (int j = 0; j < k; j++) {
            sum += kary[j];
        }

        if (sum == s) {
            for (int j = 0; j < k; j++) {
                weights[counter][j] = kary[j] / (double) s;
            }

            counter++;
        }
    }

    return weights;
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.core.indicator.RIndicator.java

/**
 * Converts an integer into its base-k representation.
 * //w  ww. j  a  va2 s.c o m
 * @param number the integer to convert
 * @param k the base
 * @param length the length of the resulting base-k representation
 * @return the base-k representation of the given number
 */
private static int[] toBaseK(int number, int k, int length) {
    int value = length - 1;
    int[] kary = new int[length];
    int i = 0;

    if (number >= ArithmeticUtils.pow(k, length)) {
        throw new FrameworkException(
                "number can not be represented in " + "base-k with specified number of digits");
    }

    while (number != 0) {
        if (number >= ArithmeticUtils.pow(k, value)) {
            kary[i]++;
            number -= ArithmeticUtils.pow(k, value);
        } else {
            value--;
            i++;
        }
    }

    return kary;
}

From source file:cc.redberry.physics.oneloopdiv.Averaging.java

@Override
public Tensor transform(Tensor tensor) {
    if (tensor instanceof Sum || tensor instanceof Expression) {
        int i;//from   w  ww .j  a v  a2s. co  m
        Tensor tensorCurrent, tempResult;
        Tensor[] newSumElements = new Tensor[tensor.size()];
        boolean needRebuild = false;
        for (i = tensor.size() - 1; i >= 0; --i) {
            tensorCurrent = tensor.get(i);
            tempResult = transform(tensorCurrent);
            if (tensorCurrent != tempResult)
                needRebuild = true;
            newSumElements[i] = tempResult;
        }
        if (needRebuild)
            return tensor.getFactory().create(newSumElements);
        else
            return tensor;
    }

    if (tensor instanceof Product) {
        int i;
        int count = 0;
        Tensor current, old;
        IndicesBuilder ib = new IndicesBuilder();
        List<Tensor> newProductElements = new ArrayList<>();
        for (i = tensor.size() - 1; i >= 0; --i) {
            current = tensor.get(i);
            if (isN(current)) {
                ib.append(current);
                ++count;
            } else {
                if (TensorUtils.isScalar(current)) {
                    FromChildToParentIterator iterator = new FromChildToParentIterator(current);
                    Tensor temp;
                    boolean flag = false;
                    while ((temp = iterator.next()) != null) {
                        if (isN(temp)) {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        newProductElements.add(current);
                        continue;
                    }
                    if (!(current instanceof Power) || !TensorUtils.isInteger(current.get(1))
                            || ((Complex) current.get(1)).intValue() != 2)
                        throw new IllegalArgumentException();

                    Tensor[] bases = { current.get(0), current.get(0) };
                    bases[1] = ApplyIndexMapping.renameDummy(bases[1],
                            TensorUtils.getAllIndicesNamesT(tensor).toArray());
                    flag = false;
                    for (Tensor base : bases) {
                        for (Tensor t : base) {
                            if (isN(t)) {
                                ib.append(t);
                                ++count;
                                flag = true;
                            } else
                                newProductElements.add(t);
                        }
                    }
                    if (!flag)
                        throw new IllegalArgumentException("Expand first");
                } else
                    newProductElements.add(current);
            }
        }
        if (count == 0)
            return tensor;
        if (count % 2 != 0)
            return Complex.ZERO;
        //            System.out.println(count);
        count = count / 2;
        Tensor result = average(ib.getIndices().getAllIndices().copy());
        long factor = ArithmeticUtils.pow((long) 2, count) * ArithmeticUtils.factorial(count + 1);//may be BigInteger?
        Complex number = new Complex((long) factor).reciprocal();
        result = ExpandTransformation.expand(result);
        newProductElements.add(number);
        newProductElements.add(result);
        return Tensors.multiply(newProductElements.toArray(new Tensor[newProductElements.size()]));
    }

    if (tensor instanceof Power) {
        Tensor nBase = transform(tensor.get(0));
        if (nBase == tensor.get(0))
            return tensor;
        return Tensors.pow(nBase, tensor.get(1));
    }
    return tensor;
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.core.AdaptiveGridArchive.java

/**
 * Returns the index of the specified solution in this adaptive grid
 * archive, or {@code -1} if the solution is not within the current lower
 * and upper bounds.//w  ww . j av  a  2 s .  c  o  m
 * 
 * @param solution the specified solution
 * @return the index of the specified solution in this adaptive grid
 *         archive, or {@code -1} if the solution is not within the current
 *         lower and upper bounds
 */
public int findIndex(Solution solution) {
    int index = 0;

    for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
        double value = solution.getObjective(i);

        if ((value < minimum[i]) || (value > maximum[i])) {
            return -1;
        } else {
            int tempIndex = (int) (numberOfDivisions * ((value - minimum[i]) / (maximum[i] - minimum[i])));

            // handle special case where value = maximum[i]
            if (tempIndex == numberOfDivisions) {
                tempIndex--;
            }

            index += tempIndex * ArithmeticUtils.pow(numberOfDivisions, i);
        }
    }

    return index;
}

From source file:org.gitools.analysis.groupcomparison.format.math33Preview.CombinatoricsUtils.java

/**
 * Returns the <a//from w ww. j  a v a 2s  .c  o  m
 * href="http://mathworld.wolfram.com/StirlingNumberoftheSecondKind.html">
 * Stirling number of the second kind</a>, "{@code S(n, k)}", the number of
 * ways of partitioning an {@code n}-element set into {@code k} non-empty
 * subsets.
 * <p>
 * The preconditions are {@code 0 <= k <= n } (otherwise
 * {@code NotPositiveException} is thrown)
 * </p>
 *
 * @param n the size of the set
 * @param k the number of non-empty subsets
 * @return {@code S(n, k)}
 * @throws NotPositiveException      if {@code k < 0}.
 * @throws NumberIsTooLargeException if {@code k > n}.
 * @throws MathArithmeticException   if some overflow happens, typically for n exceeding 25 and
 *                                   k between 20 and n-2 (S(n,n-1) is handled specifically and does not overflow)
 * @since 3.1
 */
public static long stirlingS2(final int n, final int k)
        throws NotPositiveException, NumberIsTooLargeException, MathArithmeticException {
    if (k < 0) {
        throw new NotPositiveException(k);
    }
    if (k > n) {
        throw new NumberIsTooLargeException(k, n, true);
    }

    long[][] stirlingS2 = STIRLING_S2.get();

    if (stirlingS2 == null) {
        // the cache has never been initialized, compute the first numbers
        // by direct recurrence relation

        // as S(26,9) = 11201516780955125625 is larger than Long.MAX_VALUE
        // we must stop computation at row 26
        final int maxIndex = 26;
        stirlingS2 = new long[maxIndex][];
        stirlingS2[0] = new long[] { 1l };
        for (int i = 1; i < stirlingS2.length; ++i) {
            stirlingS2[i] = new long[i + 1];
            stirlingS2[i][0] = 0;
            stirlingS2[i][1] = 1;
            stirlingS2[i][i] = 1;
            for (int j = 2; j < i; ++j) {
                stirlingS2[i][j] = j * stirlingS2[i - 1][j] + stirlingS2[i - 1][j - 1];
            }
        }

        // atomically save the cache
        STIRLING_S2.compareAndSet(null, stirlingS2);

    }

    if (n < stirlingS2.length) {
        // the number is in the small cache
        return stirlingS2[n][k];
    } else {
        // use explicit formula to compute the number without caching it
        if (k == 0) {
            return 0;
        } else if (k == 1 || k == n) {
            return 1;
        } else if (k == 2) {
            return (1l << (n - 1)) - 1l;
        } else if (k == n - 1) {
            return binomialCoefficient(n, 2);
        } else {
            // definition formula: note that this may trigger some overflow
            long sum = 0;
            long sign = ((k & 0x1) == 0) ? 1 : -1;
            for (int j = 1; j <= k; ++j) {
                sign = -sign;
                sum += sign * binomialCoefficient(k, j) * ArithmeticUtils.pow(j, n);
                if (sum < 0) {
                    // there was an overflow somewhere
                    throw new MathArithmeticException(LocalizedFormats.ARGUMENT_OUTSIDE_DOMAIN, n, 0,
                            stirlingS2.length - 1);
                }
            }
            return sum / factorial(k);
        }
    }

}