Example usage for java.math BigInteger compareTo

List of usage examples for java.math BigInteger compareTo

Introduction

In this page you can find the example usage for java.math BigInteger compareTo.

Prototype

public int compareTo(BigInteger val) 

Source Link

Document

Compares this BigInteger with the specified BigInteger.

Usage

From source file:Main.java

/**
 * Compute the square root of x to a given scale, x >= 0. Use Newton's
 * algorithm./*from   w ww  .j av  a 2  s  .  c  o  m*/
 * 
 * @param x
 *            the value of x
 * @return the result value
 */
public static BigDecimal sqrt(BigDecimal x) {
    // Check that x >= 0.
    if (x.signum() < 0) {
        throw new ArithmeticException("x < 0");
    }

    // n = x*(10^(2*SCALE))
    BigInteger n = x.movePointRight(SCALE << 1).toBigInteger();

    // The first approximation is the upper half of n.
    int bits = (n.bitLength() + 1) >> 1;
    BigInteger ix = n.shiftRight(bits);
    BigInteger ixPrev;

    // Loop until the approximations converge
    // (two successive approximations are equal after rounding).
    do {
        ixPrev = ix;

        // x = (x + n/x)/2
        ix = ix.add(n.divide(ix)).shiftRight(1);

        Thread.yield();
    } while (ix.compareTo(ixPrev) != 0);

    return new BigDecimal(ix, SCALE);
}

From source file:org.openestate.io.daft_ie.DaftIeUtils.java

public static String printPositiveInteger(BigInteger value) {
    if (value == null || value.compareTo(BigInteger.ZERO) < 1)
        throw new IllegalArgumentException("Can't print positive integer value!");
    else/*w w w  .  jav a2  s.c  om*/
        return DatatypeConverter.printInteger(value);
}

From source file:com.amazonaws.services.kinesis.clientlibrary.proxies.util.KinesisLocalFileDataCreator.java

/**
 * Creates a temp file (in default temp file location) with fake Kinesis data records.
 * Records will be put in all shards.// w  w w. j  av  a 2  s  . c o m
 * @param fileNamePrefix Prefix for the name of the temp file
 * @param shardList List of shards (we use the shardId and sequenceNumberRange fields)
 * @param numRecordsPerShard Num records per shard (the shard sequenceNumberRange should be large enough
 *     for us to allow these many records with some "holes")
 * @return File with stream data filled in
 * @throws IOException Thrown if there are issues creating/updating the file
 */
public static File generateTempDataFile(List<Shard> shardList, int numRecordsPerShard, String fileNamePrefix)
        throws IOException {
    File file = File.createTempFile(fileNamePrefix, FILE_NAME_SUFFIX);
    try (BufferedWriter fileWriter = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) {
        ObjectMapper objectMapper = new ObjectMapper();
        String serializedShardList = objectMapper
                .writeValueAsString(new KinesisLocalFileProxy.SerializedShardList(shardList));
        fileWriter.write(serializedShardList);
        fileWriter.newLine();
        BigInteger sequenceNumberIncrement = new BigInteger("0");
        long timestamp = STARTING_TIMESTAMP;
        for (int i = 0; i < numRecordsPerShard; i++) {
            for (Shard shard : shardList) {
                BigInteger sequenceNumber = new BigInteger(
                        shard.getSequenceNumberRange().getStartingSequenceNumber())
                                .add(sequenceNumberIncrement);
                String endingSequenceNumber = shard.getSequenceNumberRange().getEndingSequenceNumber();
                BigInteger maxSequenceNumber = KinesisLocalFileProxy.MAX_SEQUENCE_NUMBER;
                if (endingSequenceNumber != null) {
                    maxSequenceNumber = new BigInteger(endingSequenceNumber);
                }
                if (maxSequenceNumber.compareTo(sequenceNumber) != 1) {
                    throw new IllegalArgumentException("Not enough space in shard");
                }
                String partitionKey = PARTITION_KEY_PREFIX + shard.getShardId()
                        + generateRandomString(PARTITION_KEY_LENGTH);
                String data = generateRandomString(DATA_LENGTH);

                // Allow few records to have the same timestamps (to mimic real life scenarios).
                timestamp = (i % DIVISOR == 0) ? timestamp : timestamp + 1;
                String line = shard.getShardId() + "," + sequenceNumber + "," + partitionKey + "," + data + ","
                        + timestamp;

                fileWriter.write(line);
                fileWriter.newLine();
                sequenceNumberIncrement = sequenceNumberIncrement.add(BigInteger.ONE);
                sequenceNumberIncrement = sequenceNumberIncrement
                        .add(new BigInteger(NUM_BITS, randomGenerator));
            }
        }
    }
    return file;
}

From source file:org.openestate.io.immoxml.ImmoXmlUtils.java

public static String printPositiveInteger(BigInteger value) {
    // ImmoXML specifies positive integer values excluding 0
    if (value == null || value.compareTo(BigInteger.ZERO) < 1)
        throw new IllegalArgumentException("Can't print positive integer value!");
    else//from   w  w  w.  j av a  2s . c om
        return printInteger(value);
}

From source file:strat.mining.stratum.proxy.utils.mining.SHA256HashingUtils.java

/**
 * Return true if the block header SHA256 hash is below the given target.
 * /*from  w  w w  .j  a v  a2  s. co m*/
 * @param target
 * @param blockHeader
 * 
 * @return
 */
public static boolean isBlockHeaderSHA256HashBelowTarget(String blockHeader, BigInteger target) {
    BigInteger hash = getBlockHeaderHash(blockHeader);

    // Check that the hash is less than the target. (The hash is valid if
    // hash < target)
    boolean isBelowTarget = hash.compareTo(target) < 0;

    return isBelowTarget;
}

From source file:org.openestate.io.openimmo.OpenImmoUtils.java

public static String printPositiveInteger(BigInteger value) {
    // OpenImmo specifies positive integer values excluding 0
    if (value == null || value.compareTo(BigInteger.ZERO) < 1)
        throw new IllegalArgumentException("Can't print positive integer value!");
    else/*from   ww  w . java 2  s .  c o  m*/
        return printInteger(value);
}

From source file:org.openestate.io.kyero.KyeroUtils.java

public static String printNonNegativeInteger(BigInteger value) {
    if (value == null || value.compareTo(BigInteger.ZERO) == -1)
        throw new IllegalArgumentException("Can't print integer value '" + value + "'!");
    else//  w ww  .j ava 2  s  . co  m
        return DatatypeConverter.printInteger(value);
}

From source file:piuk.blockchain.android.util.WalletUtils.java

public static String formatValue(final BigInteger value, final String plusSign, final String minusSign) {
    final boolean negative = value.compareTo(BigInteger.ZERO) < 0;
    final BigInteger absValue = value.abs();

    final String sign = negative ? minusSign : plusSign;

    final int coins = absValue.divide(Utils.COIN).intValue();
    final int cents = absValue.remainder(Utils.COIN).intValue();

    if (cents % 1000000 == 0)
        return String.format("%s%d.%02d", sign, coins, cents / 1000000);
    else if (cents % 10000 == 0)
        return String.format("%s%d.%04d", sign, coins, cents / 10000);
    else//from  w w  w  .  j  a v a  2  s.c o  m
        return String.format("%s%d.%08d", sign, coins, cents);
}

From source file:com.guldencoin.androidwallet.nlg.ui.RequestCoinsFragment.java

private static byte[] createPaymentRequest(final BigInteger amount, @Nonnull final Address toAddress,
        final String memo, final String paymentUrl) {
    if (amount != null && amount.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0)
        throw new IllegalArgumentException("amount too big for protobuf: " + amount);

    final Protos.Output.Builder output = Protos.Output.newBuilder();
    output.setAmount(amount != null ? amount.longValue() : 0);
    output.setScript(ByteString.copyFrom(ScriptBuilder.createOutputScript(toAddress).getProgram()));

    final Protos.PaymentDetails.Builder paymentDetails = Protos.PaymentDetails.newBuilder();
    paymentDetails.setNetwork(Constants.NETWORK_PARAMETERS.getPaymentProtocolId());
    paymentDetails.addOutputs(output);/*w w w  . j a  v  a 2 s . c om*/
    if (memo != null)
        paymentDetails.setMemo(memo);
    if (paymentUrl != null)
        paymentDetails.setPaymentUrl(paymentUrl);
    paymentDetails.setTime(System.currentTimeMillis());

    final Protos.PaymentRequest.Builder paymentRequest = Protos.PaymentRequest.newBuilder();
    paymentRequest.setSerializedPaymentDetails(paymentDetails.build().toByteString());

    return paymentRequest.build().toByteArray();
}

From source file:com.bigdata.dastor.utils.FBUtilities.java

/**
 * Given two bit arrays represented as BigIntegers, containing the given
 * number of significant bits, calculate a midpoint.
 *
 * @param left The left point./*from w  ww  . j a va 2 s.  c o  m*/
 * @param right The right point.
 * @param sigbits The number of bits in the points that are significant.
 * @return A midpoint that will compare bitwise halfway between the params, and
 * a boolean representing whether a non-zero lsbit remainder was generated.
 */
public static Pair<BigInteger, Boolean> midpoint(BigInteger left, BigInteger right, int sigbits) {
    BigInteger midpoint;
    boolean remainder;
    if (left.compareTo(right) < 0) {
        BigInteger sum = left.add(right);
        remainder = sum.testBit(0);
        midpoint = sum.shiftRight(1);
    } else {
        BigInteger max = TWO.pow(sigbits);
        // wrapping case
        BigInteger distance = max.add(right).subtract(left);
        remainder = distance.testBit(0);
        midpoint = distance.shiftRight(1).add(left).mod(max);
    }
    return new Pair(midpoint, remainder);
}