Java Code Examples for java.math.BigDecimal#equals()

The following examples show how to use java.math.BigDecimal#equals() . These examples are extracted from open source projects. 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 Project: Bats   File: StandardConvertletTable.java    License: Apache License 2.0 6 votes vote down vote up
private static RexNode divide(RexBuilder rexBuilder, RexNode res,
    BigDecimal val) {
  if (val.equals(BigDecimal.ONE)) {
    return res;
  }
  // If val is between 0 and 1, rather than divide by val, multiply by its
  // reciprocal. For example, rather than divide by 0.001 multiply by 1000.
  if (val.compareTo(BigDecimal.ONE) < 0
      && val.signum() == 1) {
    try {
      final BigDecimal reciprocal =
          BigDecimal.ONE.divide(val, RoundingMode.UNNECESSARY);
      return multiply(rexBuilder, res,
          rexBuilder.makeExactLiteral(reciprocal));
    } catch (ArithmeticException e) {
      // ignore - reciprocal is not an integer
    }
  }
  return divideInt(rexBuilder, res, rexBuilder.makeExactLiteral(val));
}
 
Example 2
public static BigDecimal pow(BigDecimal a, BigDecimal b, int scale) {
	if (a.signum() == -1) {
		throw new ArithmeticException("x < 0");
	}
	if (a.equals(BigDecimal.ZERO)) {
		return BigDecimal.ZERO;
	}
	scale = Math.max(Math.max(a.precision(), b.precision()), scale) + 1;
	MathContext mc = new MathContext(scale, RoundingMode.HALF_UP);
	BigDecimal remainer = b.remainder(BigDecimal.ONE, mc);
	if (remainer.equals(BigDecimal.ZERO)) {
		return a.pow(b.intValue(), mc);
	}
	// else we have to do the more expansive route:
	// a^b=exp(b*ln(a)) 
	return exp(b.multiply(ln(a, scale), mc), scale).setScale(scale - 1, RoundingMode.HALF_EVEN);
}
 
Example 3
Source Project: Quicksql   File: RexImpTable.java    License: MIT License 6 votes vote down vote up
/** Multiplies an expression by a constant and divides by another constant,
 * optimizing appropriately.
 *
 * <p>For example, {@code multiplyDivide(e, 10, 1000)} returns
 * {@code e / 100}. */
public static Expression multiplyDivide(Expression e, BigDecimal multiplier,
    BigDecimal divider) {
  if (multiplier.equals(BigDecimal.ONE)) {
    if (divider.equals(BigDecimal.ONE)) {
      return e;
    }
    return Expressions.divide(e,
        Expressions.constant(divider.intValueExact()));
  }
  final BigDecimal x =
      multiplier.divide(divider, RoundingMode.UNNECESSARY);
  switch (x.compareTo(BigDecimal.ONE)) {
  case 0:
    return e;
  case 1:
    return Expressions.multiply(e, Expressions.constant(x.intValueExact()));
  case -1:
    return multiplyDivide(e, BigDecimal.ONE, x);
  default:
    throw new AssertionError();
  }
}
 
Example 4
Source Project: CRF   File: CrfUtilities.java    License: MIT License 6 votes vote down vote up
/**
 * If |value1|>|value2| returns |value1|/|value2|. Otherwise returns |value2|/|value1|.
 */
public static BigDecimal relativeDifference(BigDecimal value1, BigDecimal value2)
{
	if (value1.equals(value2))  {return BigDecimal.ONE;}
	
	value1 = value1.abs();
	value2 = value2.abs();
	
	BigDecimal smaller;
	BigDecimal larger;
	if (value1.compareTo(value2)<0)
	{
		smaller = value1;
		larger = value2;
	}
	else
	{
		smaller = value2;
		larger = value1;
	}
	
	BigDecimal ret = safeDivide(larger, smaller);
	return ret;
}
 
Example 5
private static int addTest(BigDecimal arg1, BigDecimal arg2, BigDecimal expectedResult) {
    int failures = 0;
    BigDecimal result = arg1.add(arg2);
    if (!result.equals(expectedResult)) {
        System.out.println("Sum:" +
                arg1 + " + " +
                arg2 + " == " +
                result + "; expected  " +
                expectedResult
        );
        failures++;
    }
    result = arg2.add(arg1);
    if (!result.equals(expectedResult)) {
        System.out.println("Sum:" +
                arg2 + " + " +
                arg1 + " == " +
                result + "; expected  " +
                expectedResult
        );
        failures++;
    }
    return failures;
}
 
Example 6
Source Project: jsr354-ri   File: Money.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Money divide(Number divisor) {
    if (NumberVerifier.isInfinityAndNotNaN(divisor)) {
        return Money.of(0, getCurrency());
    }
    BigDecimal divisorBD = MoneyUtils.getBigDecimal(divisor);
    if (divisorBD.equals(BigDecimal.ONE)) {
        return this;
    }
    MathContext mc = MoneyUtils.getMathContext(monetaryContext, RoundingMode.HALF_EVEN);
    int maxScale = monetaryContext.getMaxScale();
    if(maxScale>0){
        return new Money(this.number.divide(divisorBD, maxScale, mc.getRoundingMode()), getCurrency(), monetaryContext);
    }
    return new Money(this.number.divide(divisorBD, mc), getCurrency(), monetaryContext);
}
 
Example 7
private static int addTest(BigDecimal arg1, BigDecimal arg2, BigDecimal expectedResult) {
    int failures = 0;
    BigDecimal result = arg1.add(arg2);
    if (!result.equals(expectedResult)) {
        System.out.println("Sum:" +
                arg1 + " + " +
                arg2 + " == " +
                result + "; expected  " +
                expectedResult
        );
        failures++;
    }
    result = arg2.add(arg1);
    if (!result.equals(expectedResult)) {
        System.out.println("Sum:" +
                arg2 + " + " +
                arg1 + " == " +
                result + "; expected  " +
                expectedResult
        );
        failures++;
    }
    return failures;
}
 
Example 8
private static int addTest(BigDecimal arg1, BigDecimal arg2, BigDecimal expectedResult) {
    int failures = 0;
    BigDecimal result = arg1.add(arg2);
    if (!result.equals(expectedResult)) {
        System.out.println("Sum:" +
                arg1 + " + " +
                arg2 + " == " +
                result + "; expected  " +
                expectedResult
        );
        failures++;
    }
    result = arg2.add(arg1);
    if (!result.equals(expectedResult)) {
        System.out.println("Sum:" +
                arg2 + " + " +
                arg1 + " == " +
                result + "; expected  " +
                expectedResult
        );
        failures++;
    }
    return failures;
}
 
Example 9
Source Project: obevo   File: InternMap.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return a reference to a shared BigDecimal object if the cache holds one of the same value as the BigDecimal
 * passed in.
 * Currently the only BigDecimal cached is zero.
 *
 * @param d The BigDecimal to intern
 * @return A reference to a shared BigDecimal object if the cache holds one of the same value as the BigDecimal
 * passed in.
 */
private BigDecimal intern(BigDecimal d) {
    if (d == null) {
        return d;
    } else if (d.equals(zeroDecimal)) {
        return zeroDecimal;
    } else {
        return d;
    }
}
 
Example 10
Source Project: tddl5   File: BigDecimalType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object doDivide(Object v1, Object v2) {
    BigDecimal i1 = convertFrom(v1);
    BigDecimal i2 = convertFrom(v2);

    if (i2.equals(BigDecimal.ZERO)) {
        return null;
    }
    return i1.divide(i2, 4, BigDecimal.ROUND_HALF_UP);
}
 
Example 11
protected MithraDataObject zSetBigDecimal(BigDecimalAttribute attr, BigDecimal newValue, boolean isReadOnly, boolean hasOptimistic)
{
    newValue = com.gs.fw.common.mithra.util.BigDecimalUtil.validateBigDecimalValue(newValue, attr.getPrecision(), attr.getScale());
    TransactionalBehavior behavior = zGetTransactionalBehaviorForWriteWithWaitIfNecessary();
    try
    {
        MithraDataObject data = behavior.getCurrentDataForRead(this);
        BigDecimal cur = attr.bigDecimalValueOf(data);
        if (cur == null)
        {
            if (newValue == null) return null;
        }
        else
        {
            if (cur.equals(newValue)) return null;
        }
        data = behavior.update(this, attr, newValue, isReadOnly, true);
        if (hasOptimistic)
        {
            zIncrementOptimiticAttribute(behavior, data);
        }
        return data;
    }
    finally
    {
        behavior.clearTempTransaction(this);
    }
}
 
Example 12
Source Project: gemfirexd-oss   File: Converters.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean toBoolean(OptimizedElementArray row, int columnIndex)
    throws SQLException {
  BigDecimal bd = (BigDecimal)row.getObject(columnIndex - 1);
  if (bd != null) {
    return !bd.equals(BigDecimal.ZERO);
  }
  else {
    return false;
  }
}
 
Example 13
@Override
public String[] unparse(LoadContext context, LoadInfo info)
{
	BigDecimal mod = info.getLoadScoreMultiplier();
	if ((mod == null) || mod.equals(BigDecimal.ZERO))
	{
		return null;
	}
	return new String[]{mod.toString()};
}
 
Example 14
private static int minLongConstructorTest(MathContext mc) {
    int failures = 0;
    BigDecimal bd1 = new BigDecimal(Long.MIN_VALUE,mc);
    BigDecimal bd2 = new BigDecimal(Long.MIN_VALUE).round(mc);
    if (!bd1.equals(bd2)) {
        System.out.println("new BigDecimal(long,MathContext):" +
                "long == " +
                Long.MIN_VALUE + "; result == " +
                bd1 + "; expected  == " +
                bd2
        );
        failures++;
    }
    return failures;
}
 
Example 15
private static int minLongConstructorTest(MathContext mc) {
    int failures = 0;
    BigDecimal bd1 = new BigDecimal(Long.MIN_VALUE,mc);
    BigDecimal bd2 = new BigDecimal(Long.MIN_VALUE).round(mc);
    if (!bd1.equals(bd2)) {
        System.out.println("new BigDecimal(long,MathContext):" +
                "long == " +
                Long.MIN_VALUE + "; result == " +
                bd1 + "; expected  == " +
                bd2
        );
        failures++;
    }
    return failures;
}
 
Example 16
Source Project: calcite   File: StandardConvertletTable.java    License: Apache License 2.0 5 votes vote down vote up
private RexNode mod(RexBuilder rexBuilder, RelDataType resType, RexNode res,
    BigDecimal val) {
  if (val.equals(BigDecimal.ONE)) {
    return res;
  }
  return rexBuilder.makeCall(SqlStdOperatorTable.MOD, res,
      rexBuilder.makeExactLiteral(val, resType));
}
 
Example 17
private void oneNullNegativeTest(ResultSet rs, boolean decimal, boolean floatingPoint)
    throws SQLException {
  try {
    if (!decimal && !floatingPoint) {
      assertTrue(rs.getBoolean(1));
    }
    assertEquals(1, rs.getByte(1));
    assertEquals(1, rs.getShort(1));
    assertEquals(1, rs.getInt(1));
    assertEquals(1L, rs.getLong(1));
    assertEquals(1D, rs.getDouble(1), .000001);
    assertEquals(1F, rs.getFloat(1), .000001);
    if (decimal) {
      if (floatingPoint) {
        BigDecimal bd = rs.getBigDecimal(1);
        if (!bd.equals(new BigDecimal("1")) && !bd.equals(new BigDecimal("1.0"))) {
          fail("getBigDecimal error : is " + bd.toString());
        }
        assertEquals("1.0", rs.getString(1));

      } else {
        assertEquals(new BigDecimal("1.00000000000000000000"), rs.getBigDecimal(1));
        assertEquals("1.00000000000000000000", rs.getString(1));
      }
    } else {
      assertEquals(new BigDecimal("1"), rs.getBigDecimal(1));
      assertEquals("1", rs.getString(1));
    }
  } catch (SQLException e) {
    e.printStackTrace();
    fail("must not have thrown error");
  }

  if (rs.next()) {
    nullNegativeTest(rs, decimal);
  } else {
    fail("must have result !");
  }
}
 
Example 18
private void addEntriesParameters() {
    final List<IdentifiableEntry> identifiers = new ArrayList<>();

    if (getDocumentRequest().hasRegistration()) {
        Registration registration = getDocumentRequest().getRegistration();
        final List<DiplomaSupplementEntry> entries = new ArrayList<DiplomaSupplementEntry>();
        final Map<Unit, String> academicUnitIdentifiers = new HashMap<Unit, String>();
        Double equivalenceCredits;

        final ICurriculum curriculum = registration.getCurriculum(getDocumentRequest().getRequestedCycle());
        BigDecimal remainingCredits = curriculum.getRemainingCredits();

        for (ICurriculumEntry entry : curriculum.getCurriculumEntries()) {
            DiplomaSupplementEntry diplomaSupplementEntry = new DiplomaSupplementEntry(entry, academicUnitIdentifiers);
            if (!diplomaSupplementEntry.isEquivalence) {
                entries.add(diplomaSupplementEntry);
            }
        }

        Collections.sort(entries);
        addParameter("entries", entries);

        for (final Entry<Unit, String> entry2 : academicUnitIdentifiers.entrySet()) {
            identifiers.add(new AcademicUnitEntry(entry2));
        }

        if (!remainingCredits.equals(BigDecimal.ZERO)) {
            final StringBuilder builder = new StringBuilder();
            builder.append(BundleUtil.getString(Bundle.ACADEMIC, getLocale(), "documents.remainingCreditsInfo"));
            builder.append(": ");
            builder.append(remainingCredits.toString());
            builder.append(" ");
            builder.append(getCreditsDescription());
            builder.append(".");
            identifiers.add(new IdentifiableEntry("*", builder.toString()));
        }


    } else {
        addParameter("entries", new ArrayList<DiplomaSupplementEntry>());
    }


    addParameter("academicUnitIdentifiers", identifiers);
}
 
Example 19
Source Project: quilt   File: AimdCongestionController.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * <p>Properly handle a rejection containing a {@link InterledgerErrorCode#F08_AMOUNT_TOO_LARGE} error code.</p>
 *
 * <p>The goal of this method is to reduce the {@link #maxPacketAmount} (if present) or set a maximum amount if no
 * value is present for {@link #maxPacketAmount}. This is because an F08 error fundamentally means the ILPv4 packet is
 * too big (see NOTE below). In order to do this, this function will first look into the data payload returned by the
 * Connector in {@link InterledgerRejectPacket#getData()}. If values can be computed from here, they will be.
 * Otherwise, the new `maxPacketAmount` will simply be half of {@code prepAmount}, or {@link UnsignedLong#ONE},
 * whichever is greater.</p>
 *
 * <p>
 * NOTE: This condition is not inherently a STREAM error, but is instead an ILPv4 error. From the ILPv4 RFC, an F08
 * error means: "The packet amount is higher than the maximum a connector is willing to forward. Senders MAY send
 * another packet with a lower amount. Connectors that produce this error SHOULD encode the amount they received and
 * their maximum in the data to help senders determine how much lower the packet amount should be." Thus, we can check
 * for an AmountTooLargeErrorData in the reject packet's data. If found, we use it. If not found, we just reduce by
 * the max packet amount by half of the prepared amount (because this value was too high, triggering the F08).
 * </p>
 *
 * @param prepareAmount An {@link UnsignedLong} representing the amount that was originally prepared to the immediate
 *                      peer inside of an {@link InterledgerPreparePacket}.
 * @param rejectPacket  The {@link InterledgerRejectPacket} that was returned from the immediate peer.
 *
 * @return An {@link UnsignedLong} representing the new value of {@link #maxPacketAmount}.
 */
@VisibleForTesting
protected UnsignedLong handleF08Rejection(
    final UnsignedLong prepareAmount, final InterledgerRejectPacket rejectPacket
) {
  Objects.requireNonNull(prepareAmount, "prepareAmount must not be null");
  Objects.requireNonNull(rejectPacket, "rejectPacket must not be null");

  // Compute the newMaxPacketAmount
  UnsignedLong newMaxPacketAmount;
  if (rejectPacket.getData().length > 0) {
    try {
      // Assume there's error data, because their should be.
      final AmountTooLargeErrorData amountTooLargeErrorData =
          streamCodecContext.read(AmountTooLargeErrorData.class, new ByteArrayInputStream(rejectPacket.getData()));

      final BigDecimal prepareAmountAsBigDecimal = new BigDecimal(prepareAmount.bigIntegerValue());
      final BigDecimal detailsMaxAmount = new BigDecimal(amountTooLargeErrorData.maximumAmount().bigIntegerValue());
      final BigDecimal detailsAmountReceived = new BigDecimal(
          amountTooLargeErrorData.receivedAmount().bigIntegerValue());

      if (detailsAmountReceived.equals(BigDecimal.ZERO)) {
        newMaxPacketAmount = halvePrepareAmount(prepareAmount);
      } else {
        // Prepared 10, but only sent 3, max is 2
        // receivedAmount: Local amount received by the connector
        // maxAmount: Maximum amount (inclusive, denominated in same units as the receivedAmount) the connector
        // will forward
        // Equation: new_max_packet_amount = prepare_amount * details.max_amount() / details.amount_received();
        final BigDecimal newMaxPacketAmountAsBigDecimal =
            prepareAmountAsBigDecimal.multiply(detailsMaxAmount).divide(detailsAmountReceived, RoundingMode.FLOOR);
        newMaxPacketAmount = UnsignedLong.valueOf(newMaxPacketAmountAsBigDecimal.toBigIntegerExact());
      }
    } catch (Exception e) {
      // log a warning, but otherwise eat this exception. We'll continue on using default reduction values.
      logger.warn("Unable to decode AmountTooLargeErrorData from F08 Reject packet. Setting newMaxPacketAmount to be "
          + "half the prepare amount. rejectPacket={} error={}", rejectPacket, e
      );
      newMaxPacketAmount = halvePrepareAmount(prepareAmount);
    }
  } else {
    newMaxPacketAmount = halvePrepareAmount(prepareAmount);
    logger.warn(
        "F08 Reject packet had no data payload.  Setting newMaxPacketAmount to be {} (half the prepare amount)",
        newMaxPacketAmount
    );
  }

  final UnsignedLong newMaxPacketAmountFinal = newMaxPacketAmount;
  return this.maxPacketAmount
      // If maxPacketAmount is present, take the lower of it or newMaxPacketAmount
      .map($ -> StreamUtils.min($, newMaxPacketAmountFinal))
      // Otherwise, just use newMaxPacketAmount
      .orElse(newMaxPacketAmount);
}
 
Example 20
/**
 * Compares and returns the result. If one of them or both are null, false
 * is returned.
 * 
 * @param expected
 *            the value to which will be scaled
 * @param comparator
 *            the value to be compared to
 * @return true if the values are equal to the same scale
 */
public static boolean isEqual(BigDecimal expected, BigDecimal comparator) {
    if (expected == null || comparator == null) {
        return false;
    }
    return expected.equals(comparator.setScale(expected.scale(),
            RoundingMode.HALF_UP));
}