private void testDiv(BigInteger i1, BigInteger i2) {
    BigInteger q = i1.divide(i2);
    BigInteger r = i1.remainder(i2);
    BigInteger[] temp = i1.divideAndRemainder(i2);

    assertTrue("divide and divideAndRemainder do not agree", q.equals(temp[0]));
    assertTrue("remainder and divideAndRemainder do not agree", r.equals(temp[1]));
    assertTrue(
        "signum and equals(zero) do not agree on quotient", q.signum() != 0 || q.equals(zero));
    assertTrue(
        "signum and equals(zero) do not agree on remainder", r.signum() != 0 || r.equals(zero));
    assertTrue(
        "wrong sign on quotient", q.signum() == 0 || q.signum() == i1.signum() * i2.signum());
    assertTrue("wrong sign on remainder", r.signum() == 0 || r.signum() == i1.signum());
    assertTrue("remainder out of range", r.abs().compareTo(i2.abs()) < 0);
    assertTrue("quotient too small", q.abs().add(one).multiply(i2.abs()).compareTo(i1.abs()) > 0);
    assertTrue("quotient too large", q.abs().multiply(i2.abs()).compareTo(i1.abs()) <= 0);
    BigInteger p = q.multiply(i2);
    BigInteger a = p.add(r);
    assertTrue("(a/b)*b+(a%b) != a", a.equals(i1));
    try {
      BigInteger mod = i1.mod(i2);
      assertTrue("mod is negative", mod.signum() >= 0);
      assertTrue("mod out of range", mod.abs().compareTo(i2.abs()) < 0);
      assertTrue("positive remainder == mod", r.signum() < 0 || r.equals(mod));
      assertTrue(
          "negative remainder == mod - divisor", r.signum() >= 0 || r.equals(mod.subtract(i2)));
    } catch (ArithmeticException e) {
      assertTrue("mod fails on negative divisor only", i2.signum() <= 0);
    }
  }
 /** @tests java.math.BigInteger#abs() */
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     notes = "",
     method = "abs",
     args = {})
 public void test_abs() {
   assertTrue(
       "Invalid number returned for zillion", aZillion.negate().abs().equals(aZillion.abs()));
   assertTrue("Invalid number returned for zero neg", zero.negate().abs().equals(zero));
   assertTrue("Invalid number returned for zero", zero.abs().equals(zero));
   assertTrue("Invalid number returned for two", two.negate().abs().equals(two));
 }
 public boolean checkCandidateCol(
     BigFraction[][] matrix, int pivot, int row, int col, int rowResult) {
   final BigInteger num = matrix[row][col].getNumerator();
   final BigInteger den = matrix[row][col].getDenominator();
   final int pro = num.abs().bitLength() * den.abs().bitLength();
   if (pro < pivPro) {
     pivCol = col;
     pivRow = row;
     pivPro = pro;
   }
   // if we have a 1 or a -1, we can stop
   return pivPro != 1;
 }
 public boolean checkCandidateCol(
     BigFraction[][] matrix, int pivot, int row, int col, int rowResult) {
   final BigInteger num = matrix[row][col].getNumerator();
   final BigInteger den = matrix[row][col].getDenominator();
   final int pro = num.abs().bitLength() * den.abs().bitLength();
   if (pro <= pivPro) {
     pivCol = col;
     pivRow = row;
     pivPro = pro;
   }
   // we must always continue, since subsequent 1's are preferred
   return true;
 }
Example #5
0
 // Try to convert the specified value.
 private static Number convert(Number value, UnitConverter cvtr, MathContext ctx) {
   if (cvtr instanceof RationalConverter) { // Try converting through Field
     // methods.
     RationalConverter rCvtr = (RationalConverter) cvtr;
     BigInteger dividend = rCvtr.getDividend();
     BigInteger divisor = rCvtr.getDivisor();
     if (dividend.abs().compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0)
       throw new ArithmeticException("Multiplier overflow");
     if (divisor.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0)
       throw new ArithmeticException("Divisor overflow");
     return (value.longValue() * dividend.longValue()) / (divisor.longValue());
   } else if (cvtr instanceof AbstractConverter.Compound
       && cvtr.isLinear()) { // Do it in two parts.
     AbstractConverter.Compound compound = (AbstractConverter.Compound) cvtr;
     Number firstConversion = convert(value, compound.getRight(), ctx);
     Number secondConversion = convert(firstConversion, compound.getLeft(), ctx);
     return secondConversion;
   } else { // Try using BigDecimal as intermediate.
     BigDecimal decimalValue = BigDecimal.valueOf(value.doubleValue());
     Number newValue = cvtr.convert(decimalValue.toBigDecimal(), ctx);
     return newValue;
     // if (((FieldNumber)value) instanceof Decimal)
     // return (N)((FieldNumber)Decimal.valueOf(newValue));
     // if (((FieldNumber)value) instanceof Float64)
     // return (N)((FieldNumber)Float64.valueOf(newValue.doubleValue()));
     // throw new ArithmeticException(
     // "Generic amount conversion not implemented for amount of type " +
     // value.getClass());
   }
 }
Example #6
0
 protected BigInteger modReduce(BigInteger x) {
   if (r != null) {
     boolean negative = x.signum() < 0;
     if (negative) {
       x = x.abs();
     }
     int qLen = q.bitLength();
     boolean rIsOne = r.equals(ECConstants.ONE);
     while (x.bitLength() > (qLen + 1)) {
       BigInteger u = x.shiftRight(qLen);
       BigInteger v = x.subtract(u.shiftLeft(qLen));
       if (!rIsOne) {
         u = u.multiply(r);
       }
       x = u.add(v);
     }
     while (x.compareTo(q) >= 0) {
       x = x.subtract(q);
     }
     if (negative && x.signum() != 0) {
       x = q.subtract(x);
     }
   } else {
     x = x.mod(q);
   }
   return x;
 }
 public boolean checkCandidateCol(
     BigFraction[][] matrix, int pivot, int row, int col, int zerCnt) {
   final BigInteger num = matrix[row][col].getNumerator();
   final BigInteger den = matrix[row][col].getDenominator();
   final int len = Math.max(num.abs().bitLength(), den.abs().bitLength());
   if (len < pivLen || len == pivLen && zerCnt > pivCnt) {
     pivCol = col;
     pivRow = row;
     pivLen = len;
     pivCnt = zerCnt;
   }
   // if we have a 1 or a -1, we can stop if we have the maximum
   // possible number of zeros
   final int cols = matrix[row].length;
   return pivLen != 1 || pivCnt < cols - 1;
 }
  @TruffleBoundary
  @Specialization(guards = "isRubyBignum(value)")
  public byte[] format(int width, int precision, DynamicObject value) {
    final BigInteger bigInteger = Layouts.BIGNUM.getValue(value);
    final boolean isNegative = bigInteger.signum() == -1;
    final boolean negativeAndPadded = isNegative && (this.hasSpaceFlag || this.hasPlusFlag);

    final String formatted;
    if (negativeAndPadded) {
      formatted = bigInteger.abs().toString(2);
    } else if (!isNegative) {
      formatted = bigInteger.toString(2);
    } else {
      StringBuilder builder = new StringBuilder();
      final byte[] bytes = bigInteger.toByteArray();
      for (byte b : bytes) {
        builder.append(Integer.toBinaryString(b & 0xFF));
      }
      formatted = builder.toString();
    }
    return getFormattedString(
        formatted,
        width,
        precision,
        isNegative,
        this.hasSpaceFlag,
        this.hasPlusFlag,
        this.hasZeroFlag,
        this.useAlternativeFormat,
        this.hasMinusFlag,
        this.format);
  }
  /**
   * Write a BigDecimal value to the output stream.
   *
   * @param value The BigDecimal value to write.
   * @throws IOException
   */
  void write(BigDecimal value) throws IOException {

    if (value == null) {
      write((byte) 0);
    } else {
      byte signum = (byte) (value.signum() < 0 ? 0 : 1);
      BigInteger bi = value.unscaledValue();
      byte mantisse[] = bi.abs().toByteArray();
      byte len = (byte) (mantisse.length + 1);

      if (len > getMaxDecimalBytes()) {
        // Should never happen now as value is normalized elsewhere
        throw new IOException("BigDecimal to big to send");
      }

      if (socket.serverType == Driver.SYBASE) {
        write((byte) len);
        // Sybase TDS5 stores MSB first opposite sign!
        // length, prec, scale already sent in parameter descriptor.
        write((byte) ((signum == 0) ? 1 : 0));

        for (int i = 0; i < mantisse.length; i++) {
          write((byte) mantisse[i]);
        }
      } else {
        write((byte) len);
        write((byte) signum);

        for (int i = mantisse.length - 1; i >= 0; i--) {
          write((byte) mantisse[i]);
        }
      }
    }
  }
Example #10
0
 // c: rand_int
 private static IRubyObject randInt(
     ThreadContext context, RandomType random, RubyInteger vmax, boolean restrictive) {
   if (vmax instanceof RubyFixnum) {
     long max = RubyNumeric.fix2long(vmax);
     if (max == 0) {
       return context.nil;
     }
     if (max < 0) {
       if (restrictive) {
         return context.nil;
       }
       max = -max;
     }
     return randLimitedFixnum(context, random, max - 1);
   } else {
     BigInteger big = vmax.getBigIntegerValue();
     if (big.equals(BigInteger.ZERO)) {
       return context.nil;
     }
     if (big.signum() < 0) {
       if (restrictive) {
         return context.nil;
       }
       big = big.abs();
     }
     big = big.subtract(BigInteger.ONE);
     return randLimitedBignum(context, random, RubyBignum.newBignum(context.runtime, big));
   }
 }
Example #11
0
  public void set(BigInteger num, BigInteger denom) {
    if (denom.equals(BigInteger.ZERO))
      throw new ArithmeticException("Denominator in fraction cannot be zero: " + num + "/" + denom);

    int sign = denom.signum();
    denom = denom.abs();
    if (sign < 0) num = num.negate();

    this.num = num;
    this.denom = denom;
  }
 // Create a gravatar image based on the hash value obtained from userId
 private static String getProfileUrl(final String userId) {
   String hex = "";
   try {
     final MessageDigest digest = MessageDigest.getInstance("MD5");
     final byte[] hash = digest.digest(userId.getBytes());
     final BigInteger bigInt = new BigInteger(hash);
     hex = bigInt.abs().toString(16);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return "http://www.gravatar.com/avatar/" + hex + "?d=identicon";
 }
Example #13
0
 private static BigInteger standardDeviation(List<BigInteger> list) {
   System.out.println(list);
   BigInteger standradDeviation = new BigInteger("0");
   BigInteger sum = new BigInteger("0");
   for (BigInteger num : list) {
     sum = sum.add(num);
   }
   BigInteger average = sum.divide(new BigInteger(String.valueOf(list.size())));
   for (BigInteger num : list) {
     BigInteger diff = num.subtract(average);
     diff = diff.abs();
     BigInteger square = diff.multiply(diff);
     standradDeviation = standradDeviation.add(square);
   }
   return standradDeviation;
 }
Example #14
0
 public static Random randomFromBigInteger(BigInteger big) {
   if (big.signum() < 0) {
     big = big.abs();
   }
   byte[] buf = big.toByteArray();
   int buflen = buf.length;
   if (buf[0] == 0) {
     buflen -= 1;
   }
   int len = Math.min((buflen + 3) / 4, Random.N);
   int[] ints = bigEndianToInts(buf, len);
   if (len <= 1) {
     return new Random(ints[0]);
   } else {
     return new Random(ints);
   }
 }
  public static String formatValue(
      @Nonnull final BigInteger value,
      @Nonnull final String plusSign,
      @Nonnull final String minusSign,
      final int precision,
      final int shift) {
    BigInteger newValue = value;

    final String sign = value.signum() == -1 ? minusSign : plusSign;

    if (shift == 0) {
      if (precision == 2)
        newValue =
            value
                .subtract(value.mod(new BigInteger("1000000")))
                .add(
                    value
                        .mod(new BigInteger("1000000"))
                        .divide(new BigInteger("500000"))
                        .multiply(new BigInteger("1000000")));
      else if (precision == 4)
        newValue =
            value
                .subtract(value.mod(new BigInteger("10000")))
                .add(
                    value
                        .mod(new BigInteger("10000"))
                        .divide(new BigInteger("5000"))
                        .multiply(new BigInteger("10000")));
      else if (precision == 6)
        newValue =
            value
                .subtract(value.mod(new BigInteger("100")))
                .add(
                    value
                        .mod(new BigInteger("100"))
                        .divide(new BigInteger("50"))
                        .multiply(new BigInteger("100")));
      else if (precision == 8) ;
      else
        throw new IllegalArgumentException(
            "cannot handle precision/shift: " + precision + "/" + shift);

      final BigInteger absValue = newValue.abs();
      final long coins = (absValue.divide(new BigInteger(String.valueOf(ONE_BTC_INT)))).longValue();
      final int satoshis = (absValue.mod(new BigInteger(String.valueOf(ONE_BTC_INT))).intValue());

      if (satoshis % 1000000 == 0)
        return String.format(Locale.US, "%s%d.%02d", sign, coins, satoshis / 1000000);
      else if (satoshis % 10000 == 0)
        return String.format(Locale.US, "%s%d.%04d", sign, coins, satoshis / 10000);
      else if (satoshis % 100 == 0)
        return String.format(Locale.US, "%s%d.%06d", sign, coins, satoshis / 100);
      else return String.format(Locale.US, "%s%d.%08d", sign, coins, satoshis);
    } else if (shift == 3) {
      if (precision == 2)
        newValue =
            value
                .subtract(value.mod(new BigInteger("1000")))
                .add(
                    value
                        .mod(new BigInteger("1000"))
                        .divide(new BigInteger("500"))
                        .multiply(new BigInteger("1000")));
      else if (precision == 4)
        newValue =
            value
                .subtract(value.mod(new BigInteger("10")))
                .add(
                    value
                        .mod(new BigInteger("10"))
                        .divide(new BigInteger("5"))
                        .multiply(new BigInteger("10")));
      else if (precision == 5) ;
      else
        throw new IllegalArgumentException(
            "cannot handle precision/shift: " + precision + "/" + shift);

      final BigInteger absValue = newValue.abs();
      final long coins =
          (absValue.divide(new BigInteger(String.valueOf(ONE_MBTC_INT)))).longValue();
      final int satoshis = (absValue.mod(new BigInteger(String.valueOf(ONE_MBTC_INT))).intValue());

      if (satoshis % 1000 == 0)
        return String.format(Locale.US, "%s%d.%02d", sign, coins, satoshis / 1000);
      else if (satoshis % 10 == 0)
        return String.format(Locale.US, "%s%d.%04d", sign, coins, satoshis / 10);
      else return String.format(Locale.US, "%s%d.%05d", sign, coins, satoshis);
    } else {
      throw new IllegalArgumentException("cannot handle shift: " + shift);
    }
  }
Example #16
0
  /**
   * Returns this fraction rounded to the nearest whole number, using the given rounding mode.
   *
   * @throws ArithmeticException if RoundingMode.UNNECESSARY is used but this fraction does not
   *     exactly represent an integer.
   */
  public BigInteger round(RoundingMode roundingMode) {
    // Since fraction is always in lowest terms, this is an exact integer
    // iff the denominator is 1.
    if (this.denominator.equals(BigInteger.ONE)) {
      return this.numerator;
    }

    // If the denominator was not 1, rounding will be required.
    if (roundingMode == RoundingMode.UNNECESSARY) {
      throw new ArithmeticException("Rounding necessary");
    }

    final Set<RoundingMode> ROUND_HALF_MODES =
        EnumSet.of(RoundingMode.HALF_UP, RoundingMode.HALF_DOWN, RoundingMode.HALF_EVEN);

    BigInteger intVal = null;
    BigInteger remainder = null;

    // Note: The remainder is only needed if we are using HALF_X rounding
    // mode, and the
    // remainder is not one-half. Since computing the remainder can be a bit
    // expensive, only compute it if necessary.
    if (ROUND_HALF_MODES.contains(roundingMode) && !this.denominator.equals(BIGINT_TWO)) {
      final BigInteger[] divMod = this.numerator.divideAndRemainder(this.denominator);
      intVal = divMod[0];
      remainder = divMod[1];
    } else {
      intVal = this.numerator.divide(this.denominator);
    }

    // For HALF_X rounding modes, convert to either UP or DOWN.
    if (ROUND_HALF_MODES.contains(roundingMode)) {
      // Since fraction is always in lowest terms, the remainder is
      // exactly
      // one-half iff the denominator is 2.
      if (this.denominator.equals(BIGINT_TWO)) {
        if (roundingMode == RoundingMode.HALF_UP
            || (roundingMode == RoundingMode.HALF_EVEN && intVal.testBit(0))) {
          roundingMode = RoundingMode.UP;
        } else {
          roundingMode = RoundingMode.DOWN;
        }
      } else if (remainder.abs().compareTo(this.denominator.shiftRight(1)) <= 0) {
        // note: x.shiftRight(1) === x.divide(2)
        roundingMode = RoundingMode.DOWN;
      } else {
        roundingMode = RoundingMode.UP;
      }
    }

    // For ceiling and floor, convert to up or down (based on sign).
    if (roundingMode == RoundingMode.CEILING || roundingMode == RoundingMode.FLOOR) {
      // Use numerator.signum() instead of intVal.signum() to get correct
      // answers
      // for values between -1 and 0.
      if (this.numerator.signum() > 0) {
        if (roundingMode == RoundingMode.CEILING) {
          roundingMode = RoundingMode.UP;
        } else {
          roundingMode = RoundingMode.DOWN;
        }
      } else {
        if (roundingMode == RoundingMode.CEILING) {
          roundingMode = RoundingMode.DOWN;
        } else {
          roundingMode = RoundingMode.UP;
        }
      }
    }

    // Sanity check... at this point all possible values should be turned to
    // up or down.
    if (roundingMode != RoundingMode.UP && roundingMode != RoundingMode.DOWN) {
      throw new IllegalArgumentException("Unsupported rounding mode: " + roundingMode);
    }

    if (roundingMode == RoundingMode.UP) {
      if (this.numerator.signum() > 0) {
        intVal = intVal.add(BigInteger.ONE);
      } else {
        intVal = intVal.subtract(BigInteger.ONE);
      }
    }

    return intVal;
  }
Example #17
0
 public BigInteger getInt() {
   return bigInteger.abs();
 }