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

The following examples show how to use java.math.BigDecimal#negate() . 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: big-math   File: BigRational.java    License: MIT License 6 votes vote down vote up
private BigRational(BigDecimal num, BigDecimal denom) {
	BigDecimal n = num;
	BigDecimal d = denom;

	if (d.signum() == 0) {
		throw new ArithmeticException("Divide by zero");
	}

	if (d.signum() < 0) {
		n = n.negate();
		d = d.negate();
	}

	numerator = n;
	denominator = d;
}
 
Example 2
Source Project: qpid-jms   File: UnaryExpression.java    License: Apache License 2.0 6 votes vote down vote up
private static Number negate(Number left) {
    Class<?> clazz = left.getClass();
    if (clazz == Integer.class) {
        return Integer.valueOf(-left.intValue());
    } else if (clazz == Long.class) {
        return Long.valueOf(-left.longValue());
    } else if (clazz == Float.class) {
        return new Float(-left.floatValue());
    } else if (clazz == Double.class) {
        return new Double(-left.doubleValue());
    } else if (clazz == BigDecimal.class) {
        // We usually get a big decimal when we have Long.MIN_VALUE constant in
        // the Selector. Long.MIN_VALUE is too big to store in a Long as a positive
        // so we store it as a Big decimal. But it gets Negated right away.. to here
        // we try to covert it back to a Long.
        BigDecimal bd = (BigDecimal) left;
        bd = bd.negate();

        if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) {
            return Long.valueOf(Long.MIN_VALUE);
        }
        return bd;
    } else {
        throw new RuntimeException("Don't know how to negate: " + left);
    }
}
 
Example 3
Source Project: Bytecoder   File: DecimalFormat.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Formats a BigDecimal to produce a string.
 * @param number    The BigDecimal to format
 * @param result    where the text is to be appended
 * @param delegate notified of locations of sub fields
 * @throws           ArithmeticException if rounding is needed with rounding
 *                   mode being set to RoundingMode.UNNECESSARY
 * @return The formatted number string
 */
StringBuffer format(BigDecimal number, StringBuffer result,
                            FieldDelegate delegate) {
    if (multiplier != 1) {
        number = number.multiply(getBigDecimalMultiplier());
    }
    boolean isNegative = number.signum() == -1;
    if (isNegative) {
        number = number.negate();
    }

    synchronized(digitList) {
        int maxIntDigits = getMaximumIntegerDigits();
        int minIntDigits = getMinimumIntegerDigits();
        int maxFraDigits = getMaximumFractionDigits();
        int minFraDigits = getMinimumFractionDigits();
        int maximumDigits = maxIntDigits + maxFraDigits;

        digitList.set(isNegative, number, useExponentialNotation ?
            ((maximumDigits < 0) ? Integer.MAX_VALUE : maximumDigits) :
            maxFraDigits, !useExponentialNotation);

        return subformat(result, delegate, isNegative, false,
            maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
    }
}
 
Example 4
/**
 * <p>Compute <code>value*signum</code> where <code>value==null</code> is treated as <code>value==0</code></p>.
 *
 * @param value Value to sanitize.
 * @param signum 0 to sanitize to 0, > 0 to sanitize to <code>value</code>, < 0 to sanitize to negative <code>value</code>.
 *
 * @return non-null {@link BigDecimal}.
 */
static BigDecimal sanitize(BigDecimal value, int signum) {
    if (signum == 0 || value == null) {
        return ZERO;
    }
    if (signum > 0) {
        return value;
    }
    return value.negate();
}
 
Example 5
/**
 * <p>Compute <code>value*signum</code> where <code>value==null</code> is treated as <code>value==0</code></p>.
 *
 * @param value Value to sanitize.
 * @param signum 0 to sanitize to 0, > 0 to sanitize to <code>value</code>, < 0 to sanitize to negative <code>value</code>.
 *
 * @return non-null {@link BigDecimal}.
 */
static BigDecimal sanitize(BigDecimal value, int signum) {
    if (signum == 0 || value == null) {
        return ZERO;
    }
    if (signum > 0) {
        return value;
    }
    return value.negate();
}
 
Example 6
public BigDecimal getSignedAmount() {
    BigDecimal signedAmount = amount;
    if (getDebitCreditMark().sign() < 0) {
        signedAmount = signedAmount.negate();
    }
    if (getDebitCreditType() == DebitCreditType.REVERSAL) {
        signedAmount = signedAmount.negate();
    }
    return signedAmount;
}
 
Example 7
Source Project: big-math   File: GammaExperiments.java    License: MIT License 5 votes vote down vote up
public static BigDecimal factorialUsingSpouge(BigDecimal x, MathContext mathContext) {
	// https://en.wikipedia.org/wiki/Spouge%27s_approximation
	MathContext mc = new MathContext(mathContext.getPrecision() * 2, mathContext.getRoundingMode());

	int a = mathContext.getPrecision() * 13 / 10;
	BigDecimal bigA = BigDecimal.valueOf(a);
	BigDecimal c0 = sqrt(pi(mc).multiply(TWO, mc), mc);

	boolean negative = false;
	BigDecimal factor = c0;
	for (int k = 1; k < a; k++) {
		BigDecimal bigK = BigDecimal.valueOf(k);
		BigDecimal ck = pow(BigDecimal.valueOf(a-k), bigK.subtract(BigDecimal.valueOf(0.5), mc), mc);
		ck = ck.multiply(exp(BigDecimal.valueOf(a-k), mc), mc);
		ck = ck.divide(factorial(k - 1), mc);
		if (negative) {
			ck = ck.negate();
		}
		factor = factor.add(ck.divide(x.add(bigK), mc), mc);
		negative = !negative;
	}

	BigDecimal result = pow(x.add(bigA, mc), x.add(BigDecimal.valueOf(0.5), mc), mc);
	result = result.multiply(exp(x.negate().subtract(bigA, mc), mc), mc);
	result = result.multiply(factor, mc);

	return result.round(mathContext);
}
 
Example 8
Source Project: rocketmq-4.3.0   File: UnaryExpression.java    License: Apache License 2.0 5 votes vote down vote up
private static Number negate(Number left) {
    Class clazz = left.getClass();
    if (clazz == Integer.class) {
        return new Integer(-left.intValue());
    } else if (clazz == Long.class) {
        return new Long(-left.longValue());
    } else if (clazz == Float.class) {
        return new Float(-left.floatValue());
    } else if (clazz == Double.class) {
        return new Double(-left.doubleValue());
    } else if (clazz == BigDecimal.class) {
        // We ussually get a big deciamal when we have Long.MIN_VALUE
        // constant in the
        // Selector. Long.MIN_VALUE is too big to store in a Long as a
        // positive so we store it
        // as a Big decimal. But it gets Negated right away.. to here we try
        // to covert it back
        // to a Long.
        BigDecimal bd = (BigDecimal) left;
        bd = bd.negate();

        if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) {
            return Long.valueOf(Long.MIN_VALUE);
        }
        return bd;
    } else {
        throw new RuntimeException("Don't know how to negate: " + left);
    }
}
 
Example 9
Source Project: calcite   File: SqlIntervalQualifier.java    License: Apache License 2.0 5 votes vote down vote up
private CalciteContextException fieldExceedsPrecisionException(
    SqlParserPos pos, int sign, BigDecimal value, TimeUnit type,
    int precision) {
  if (sign == -1) {
    value = value.negate();
  }
  return SqlUtil.newContextException(pos,
      RESOURCE.intervalFieldExceedsPrecision(
          value, type.name() + "(" + precision + ")"));
}
 
Example 10
@Override
public BigDecimal next() {
  BigInteger unscaled =
      BigInteger.valueOf(rng.nextInt((int) Math.pow(10, precision)));
  BigDecimal value = new BigDecimal(unscaled, scale);
  if (rng.nextBoolean()) {
    value = value.negate();
  }
  return value;
}
 
Example 11
Source Project: Bytecoder   File: DurationImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static void alignSigns(BigDecimal[] buf, int start, int end) {
    // align sign
    boolean touched;

    do { // repeat until all the sign bits become consistent
        touched = false;
        int s = 0; // sign of the left fields

        for (int i = start; i < end; i++) {
            if (s * buf[i].signum() < 0) {
                // this field has different sign than its left field.
                touched = true;

                // compute the number of unit that needs to be borrowed.
                // scale should be 0 in all cases
                BigDecimal borrow = buf[i].abs().divide(
                        FACTORS[i - 1],
                        0,
                        RoundingMode.UP);
                if (buf[i].signum() > 0) {
                    borrow = borrow.negate();
                }

                // update values
                buf[i - 1] = buf[i - 1].subtract(borrow);
                buf[i] = buf[i].add(borrow.multiply(FACTORS[i - 1]));
            }
            if (buf[i].signum() != 0) {
                s = buf[i].signum();
            }
        }
    } while (touched);
}
 
Example 12
private PurchaseOrder purchaseOrderLineProcess(Invoice invoice, InvoiceLine invoiceLine)
    throws AxelorException {

  PurchaseOrderLine purchaseOrderLine = invoiceLine.getPurchaseOrderLine();

  if (purchaseOrderLine == null) {
    return null;
  }

  PurchaseOrder purchaseOrder = purchaseOrderLine.getPurchaseOrder();

  BigDecimal invoicedAmountToAdd = invoiceLine.getExTaxTotal();

  // If is it a refund invoice, so we negate the amount invoiced
  if (InvoiceToolService.isRefund(invoiceLine.getInvoice())) {
    invoicedAmountToAdd = invoicedAmountToAdd.negate();
  }

  // Update invoiced amount on purchase order line
  if (!invoice.getCurrency().equals(purchaseOrder.getCurrency())
      && purchaseOrderLine.getCompanyExTaxTotal().compareTo(BigDecimal.ZERO) != 0) {
    // If the purchase order currency is different from the invoice currency, use company currency
    // to calculate a rate. This rate will be applied to purchase order line
    BigDecimal currentCompanyInvoicedAmount = invoiceLine.getCompanyExTaxTotal();
    BigDecimal rate =
        currentCompanyInvoicedAmount.divide(
            purchaseOrderLine.getCompanyExTaxTotal(), 4, RoundingMode.HALF_UP);
    invoicedAmountToAdd = rate.multiply(purchaseOrderLine.getExTaxTotal());
  }

  purchaseOrderLine.setAmountInvoiced(
      purchaseOrderLine.getAmountInvoiced().add(invoicedAmountToAdd));

  return purchaseOrder;
}
 
Example 13
private static Number negate(Number left) {
   Class clazz = left.getClass();
   if (clazz == Integer.class) {
      return -left.intValue();
   } else if (clazz == Long.class) {
      return -left.longValue();
   } else if (clazz == Float.class) {
      return -left.floatValue();
   } else if (clazz == Double.class) {
      return -left.doubleValue();
   } else if (clazz == BigDecimal.class) {
      // We ussually get a big deciamal when we have Long.MIN_VALUE
      // constant in the
      // Selector. Long.MIN_VALUE is too big to store in a Long as a
      // positive so we store it
      // as a Big decimal. But it gets Negated right away.. to here we try
      // to covert it back
      // to a Long.
      BigDecimal bd = (BigDecimal) left;
      bd = bd.negate();

      if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) {
         return Long.valueOf(Long.MIN_VALUE);
      }
      return bd;
   } else {
      throw new RuntimeException("Don't know how to negate: " + left);
   }
}
 
Example 14
Source Project: DDMQ   File: UnaryExpression.java    License: Apache License 2.0 5 votes vote down vote up
private static Number negate(Number left) {
    Class clazz = left.getClass();
    if (clazz == Integer.class) {
        return new Integer(-left.intValue());
    } else if (clazz == Long.class) {
        return new Long(-left.longValue());
    } else if (clazz == Float.class) {
        return new Float(-left.floatValue());
    } else if (clazz == Double.class) {
        return new Double(-left.doubleValue());
    } else if (clazz == BigDecimal.class) {
        // We ussually get a big deciamal when we have Long.MIN_VALUE
        // constant in the
        // Selector. Long.MIN_VALUE is too big to store in a Long as a
        // positive so we store it
        // as a Big decimal. But it gets Negated right away.. to here we try
        // to covert it back
        // to a Long.
        BigDecimal bd = (BigDecimal) left;
        bd = bd.negate();

        if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) {
            return Long.valueOf(Long.MIN_VALUE);
        }
        return bd;
    } else {
        throw new RuntimeException("Don't know how to negate: " + left);
    }
}
 
Example 15
@Override
public BigDecimal getConversionPrice(Key key, CurrencyType currency) {

    if (currency == null) {
        return null;
    }

    if (currency == getInstrumentCurrency(key)) {
        return ONE;
    }

    if (currency == getFundingCurrency(key)) {

        BigDecimal p = getMidPrice(key);

        return p == null ? null : p.negate();

    }

    return null;

}
 
Example 16
@VisibleForTesting
BigDecimal convertQuantity(BigDecimal value) {

    if (value != null) {

        if ("buy".equals(side)) {
            return value;
        }

        if ("sell".equals(side)) {
            return value.negate();
        }

    }

    return null;

}
 
Example 17
Source Project: hbase   File: TestOrderedBytes.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Test encoded value check
 */
@Test
public void testEncodedValueCheck() {
  BigDecimal longMax = BigDecimal.valueOf(Long.MAX_VALUE);
  double negInf = Double.NEGATIVE_INFINITY;
  BigDecimal negLarge = longMax.multiply(longMax).negate();
  BigDecimal negMed = new BigDecimal("-10.0");
  BigDecimal negSmall = new BigDecimal("-0.0010");
  long zero = 0L;
  BigDecimal posSmall = negSmall.negate();
  BigDecimal posMed = negMed.negate();
  BigDecimal posLarge = negLarge.negate();
  double posInf = Double.POSITIVE_INFINITY;
  double nan = Double.NaN;
  byte int8 = 100;
  short int16 = 100;
  int int32 = 100;
  long int64 = 100L;
  float float32 = 100.0f;
  double float64 = 100.0d;
  String text = "hello world.";
  byte[] blobVar = Bytes.toBytes("foo");

  int cnt = 0;
  PositionedByteRange buff = new SimplePositionedMutableByteRange(1024);
  for (Order ord : new Order[] { Order.ASCENDING, Order.DESCENDING }) {
    int o;
    o = OrderedBytes.encodeNull(buff, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, negInf, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, negLarge, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, negMed, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, negSmall, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, zero, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, posSmall, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, posMed, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, posLarge, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, posInf, ord); cnt++;
    o = OrderedBytes.encodeNumeric(buff, nan, ord); cnt++;
    o = OrderedBytes.encodeInt8(buff, int8, ord); cnt++;
    o = OrderedBytes.encodeInt16(buff, int16, ord); cnt++;
    o = OrderedBytes.encodeInt32(buff, int32, ord); cnt++;
    o = OrderedBytes.encodeInt64(buff, int64, ord); cnt++;
    o = OrderedBytes.encodeFloat32(buff, float32, ord); cnt++;
    o = OrderedBytes.encodeFloat64(buff, float64, ord); cnt++;
    o = OrderedBytes.encodeString(buff, text, ord); cnt++;
    o = OrderedBytes.encodeBlobVar(buff, blobVar, ord); cnt++;
  }

  buff.setPosition(0);
  assertEquals(OrderedBytes.length(buff), cnt);
  for (int i = 0; i < cnt; i++) {
    assertTrue(OrderedBytes.isEncodedValue(buff));
    OrderedBytes.skip(buff);
  }
}
 
Example 18
@Override
public BigDecimal getConversionPrice(Key key, CurrencyType currency) {

    if (currency == null) {
        return null;
    }

    if (currency == getInstrumentCurrency(key)) {
        return ONE;
    }

    if (currency == getFundingCurrency(key)) {

        BigDecimal p = getMidPrice(key);

        return p == null ? null : p.negate();

    }

    return null;

}
 
Example 19
Source Project: ET_Redux   File: R238_236oc.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param inputValueModels
 * @param parDerivTerms
 */
@Override
public void calculateValue (
        ValueModel[] inputValueModels,
        ConcurrentMap<String, BigDecimal> parDerivTerms ) {

    r18O_16O = inputValueModels[0];
    r270_268m = inputValueModels[1];

    BigDecimal BD2 = new BigDecimal( 2.0 );


    setValue(//
            r270_268m.getValue().//
            subtract( BD2.//
            multiply( r18O_16O.getValue() ) ) );



    BigDecimal dR238_236oc__dR270_268m = BigDecimal.ONE;
    parDerivTerms.put( "dR238_236oc__dR270_268m", dR238_236oc__dR270_268m );

    BigDecimal dR238_236oc__dR18O_16O = BD2.negate();
    parDerivTerms.put( "dR238_236oc__dR18O_16O", dR238_236oc__dR18O_16O );

}
 
Example 20
private static BigDecimal negate(BigDecimal v) {
    return v.negate();
}