Java Code Examples for java.math.BigDecimal#ZERO

The following examples show how to use java.math.BigDecimal#ZERO . 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 File: BigDecimalMath.java    From nd4j with Apache License 2.0 6 votes vote down vote up
/**
 * The hyperbolic tangent.
 *
 * @param x The argument.
 * @return The tanh(x) = sinh(x)/cosh(x).
 */
static public BigDecimal tanh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return tanh(x.negate()).negate();
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        BigDecimal xhighpr = scalePrec(x, 2);
        /* tanh(x) = (1-e^(-2x))/(1+e^(-2x)) .
         */
        BigDecimal exp2x = exp(xhighpr.multiply(new BigDecimal(-2)));
        /* The error in tanh x is err(x)/cosh^2(x).
         */


        double eps = 0.5 * x.ulp().doubleValue() / Math.pow(Math.cosh(x.doubleValue()), 2.0);
        MathContext mc = new MathContext(err2prec(Math.tanh(x.doubleValue()), eps));


        return BigDecimal.ONE.subtract(exp2x).divide(BigDecimal.ONE.add(exp2x), mc);


    }
}
 
Example 2
Source File: Timing.java    From twister2 with Apache License 2.0 6 votes vote down vote up
public static double averageDiff(String flagA, String flagB, boolean accept) {
  if (!accept) {
    return -1;
  }
  verifyTwoFlags(flagA, flagB);

  List<Long> flagALongs = timestamps.get(flagA);
  List<Long> flagBLongs = timestamps.get(flagB);

  BigDecimal totalDiffs = BigDecimal.ZERO;
  for (int i = 0; i < flagALongs.size(); i++) {
    totalDiffs = totalDiffs.add(BigDecimal.valueOf(flagBLongs.get(i))
        .subtract(BigDecimal.valueOf(flagALongs.get(i))));
  }

  //using SOUTs to bypass logging levels
  System.out.println(String.format("Total time [%s - %s] = %s%s",
      flagA, flagB, totalDiffs.toString(), timingUnitMap.get(flagA).getLabel()));
  System.out.println(String.format("Taking average for %d events", flagALongs.size()));

  double average = totalDiffs.divide(BigDecimal.valueOf(flagALongs.size()),
      RoundingMode.HALF_UP).doubleValue();
  System.out.println(String.format("Average time [%s - %s] = %f%s", flagA, flagB,
      average, timingUnitMap.get(flagA).getLabel()));
  return average;
}
 
Example 3
Source File: Supplier.java    From development with Apache License 2.0 6 votes vote down vote up
public void calculate() {
    BigDecimal supplierRevenueAmount = BigDecimal.ZERO;
    BigDecimal supplierRevenueTotalAmount = BigDecimal.ZERO;

    for (Service service : getService()) {
        service.getServiceRevenue().calculate();
        supplierRevenueAmount = supplierRevenueAmount.add(service
                .getServiceRevenue().getBrokerRevenue());
        supplierRevenueTotalAmount = supplierRevenueTotalAmount.add(service
                .getServiceRevenue().getTotalAmount());
    }
    supplierRevenueAmount = supplierRevenueAmount.setScale(
            PriceConverter.NORMALIZED_PRICE_SCALING,
            PriceConverter.ROUNDING_MODE);
    brokerRevenuePerSupplier.setAmount(supplierRevenueAmount);
    supplierRevenueTotalAmount = supplierRevenueTotalAmount.setScale(
            PriceConverter.NORMALIZED_PRICE_SCALING,
            PriceConverter.ROUNDING_MODE);
    brokerRevenuePerSupplier.setTotalAmount(supplierRevenueTotalAmount);
}
 
Example 4
Source File: MatrixOperations.java    From JavaMainRepo with Apache License 2.0 6 votes vote down vote up
public static BigDecimal[][] multiplyScalar(BigDecimal[][] a, BigDecimal x) {
	int m = a.length;
	int n = a[0].length;
	BigDecimal[][] c = new BigDecimal[m][n];
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			c[i][j] = BigDecimal.ZERO;
		}
	}
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			c[i][j] = c[i][j].add(a[i][j].multiply(x));
		}
	}
	return c;
}
 
Example 5
Source File: PriceListService.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
public BigDecimal getDiscountAmount(PriceListLine priceListLine, BigDecimal unitPrice) {

    switch (priceListLine.getTypeSelect()) {
      case PriceListLineRepository.TYPE_ADDITIONNAL:
        return priceListLine.getAmount().negate();

      case PriceListLineRepository.TYPE_DISCOUNT:
        return priceListLine.getAmount();

      case PriceListLineRepository.TYPE_REPLACE:
        return unitPrice.subtract(priceListLine.getAmount());

      default:
        return BigDecimal.ZERO;
    }
  }
 
Example 6
Source File: Functions.java    From JavaMainRepo with Apache License 2.0 6 votes vote down vote up
public static BigDecimal[][] multiplication(BigDecimal[][] matrix1, BigDecimal[][] matrix2) {

		if (matrix1[0].length == matrix2.length) {
			// the number of columns of first matrix equals the number of rows
			// of the second one
			BigDecimal[][] resultMatrix = new BigDecimal[matrix1.length][matrix2[0].length];
			BigDecimal sum = new BigDecimal("0");
			for (int i = 0; i < matrix1.length; i++)
				for (int j = 0; j < matrix1[0].length; j++) {
					for (int k = 0; k < matrix2.length; k++) {
						sum = sum.add(matrix1[i][k].multiply(matrix2[k][j]));
						resultMatrix[i][j] = sum;
					}
					sum = BigDecimal.ZERO;
				}
			return resultMatrix;
		} else {
			System.out.println("Multiplication cannot be done");
			return null;
		}

	}
 
Example 7
Source File: PriceModelAuditLogCollector.java    From development with Apache License 2.0 6 votes vote down vote up
public void editSubscriptionPrice(DataService ds, PriceModel priceModel,
        BigDecimal oldSubscriptionPrice, boolean isCreatePriceModel) {

    if (isCreatePriceModel) {
        oldSubscriptionPrice = BigDecimal.ZERO;
    }
    boolean subscriptionPriceChanged = oldSubscriptionPrice != null
            && priceModel.getPricePerPeriod().compareTo(
                    oldSubscriptionPrice) != 0;

    if (subscriptionPriceChanged) {
        BESAuditLogEntry logEntry = createLogEntry(ds,
                Operation.EDIT_SUBSCRIPTION_PRICE, priceModel);
        logEntry.addSubscriptionPrice(priceModel);
        AuditLogData.add(logEntry);
    }
}
 
Example 8
Source File: TokenRepository.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private BigDecimal getBalance(Wallet wallet, TokenInfo tokenInfo) throws Exception {
    Function function = balanceOf(wallet.address);
    NetworkInfo network = ethereumNetworkRepository.getNetworkByChain(tokenInfo.chainId);
    String responseValue = callSmartContractFunction(function, tokenInfo.address, network, wallet);

    if (responseValue == null) return BigDecimal.valueOf(-1); //early return for network error

    List<Type> response = FunctionReturnDecoder.decode(responseValue, function.getOutputParameters());
    if (response.size() == 1) {
        return new BigDecimal(((Uint256) response.get(0)).getValue());
    } else {
        return BigDecimal.ZERO;
    }
}
 
Example 9
Source File: RexBuilder.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a double-precision literal.
 */
public RexLiteral makeApproxLiteral(BigDecimal bd) {
  // Validator should catch if underflow is allowed
  // If underflow is allowed, let underflow become zero
  if (bd.doubleValue() == 0) {
    bd = BigDecimal.ZERO;
  }
  return makeApproxLiteral(bd, typeFactory.createSqlType(SqlTypeName.DOUBLE));
}
 
Example 10
Source File: Project_InvoicedAmount.java    From estatio with Apache License 2.0 5 votes vote down vote up
private BigDecimal amountWhenParentProject(){
    BigDecimal result = BigDecimal.ZERO;
    for (Project child : project.getChildren()){
        result = result.add(wrapperFactory.wrap(new Project_InvoicedAmount(child)).invoicedAmount());
    }
    return result;
}
 
Example 11
Source File: SellRequest.java    From robozonky with Apache License 2.0 5 votes vote down vote up
public SellRequest(final Investment investment) {
    this.investmentId = investment.getId();
    this.remainingPrincipal = investment.getRemainingPrincipal()
        .orElseThrow()
        .getValue();
    this.feeAmount = investment.getSmpFee()
        .orElse(Money.ZERO)
        .getValue();
    this.discount = BigDecimal.ZERO;
    this.price = investment.getSmpPrice()
        .map(Money::getValue)
        .orElse(remainingPrincipal);
}
 
Example 12
Source File: ItemFuncMinus.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public BigDecimal realOp() {
    BigDecimal val0 = args.get(0).valReal();
    BigDecimal val1 = args.get(1).valReal();
    if (this.nullValue = (args.get(0).isNull() || args.get(1).isNull()))
        return BigDecimal.ZERO;
    return val0.subtract(val1);
}
 
Example 13
Source File: ExecutionYearViewDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
public BigDecimal getAverage() {
    if (quantity > 0) {
        return sum.divide(new BigDecimal(quantity), RoundingMode.HALF_EVEN);
    } else {
        return BigDecimal.ZERO;
    }

}
 
Example 14
Source File: ElectronicInvoiceOrder.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
public BigDecimal getInvoiceShippingAmount() {
  BigDecimal total = BigDecimal.ZERO;
  for (Iterator iter = this.invoiceItems.iterator(); iter.hasNext();) {
    ElectronicInvoiceItem eii = (ElectronicInvoiceItem) iter.next();
    total = total.add(eii.getInvoiceLineShippingAmountBigDecimal());
  }
  return total;
}
 
Example 15
Source File: Bargain.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
Bargain(Quote quote, VWapT vwap) {
    super(quote.getTicker());
    this.quote = quote;
    this.vwap = vwap;

    BigDecimal idx = BigDecimal.ZERO;
    if (vwap.vwap.compareTo(quote.askprice) > 0) {
        double ep = Math.pow(Math.E, vwap.vwap.subtract(quote.askprice)
                .doubleValue());
        idx = quote.asksize.multiply(new BigDecimal(ep),
                MathContext.DECIMAL64);
    }
    index = idx;
}
 
Example 16
Source File: PersistenceExtensions.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Gets the sum of the state of a given <code>item</code> since a certain point in time.
 * The {@link PersistenceService} identified by the <code>serviceId</code> is used.
 *
 * @param item the item for which we will sum its persisted state values since <code>timestamp</code>
 * @param timestamp the point in time from which to start the summation
 * @param serviceId the name of the {@link PersistenceService} to use
 * @return the sum of the state values since the given point in time, or {@link DecimalType.ZERO} if no historic
 *         states could be found for the <code>item</code> or if <code>serviceId</code> does no refer to a
 *         {@link QueryablePersistenceService}
 */
public static DecimalType sumSince(Item item, Instant timestamp, String serviceId) {
    Iterable<HistoricItem> result = getAllStatesSince(item, timestamp, serviceId);
    Iterator<HistoricItem> it = result.iterator();

    BigDecimal sum = BigDecimal.ZERO;
    while (it.hasNext()) {
        State state = it.next().getState();
        if (state instanceof DecimalType) {
            sum = sum.add(((DecimalType) state).toBigDecimal());
        }
    }

    return new DecimalType(sum);
}
 
Example 17
Source File: MaterialService.java    From jshERP with GNU General Public License v3.0 5 votes vote down vote up
public BigDecimal parsePrice(String price, String ratio) throws Exception{
    if(StringUtil.isEmpty(price) || StringUtil.isEmpty(ratio)) {
        return BigDecimal.ZERO;
    } else {
        BigDecimal pr=new BigDecimal(price);
        BigDecimal r=new BigDecimal(ratio);
        return pr.multiply(r);
    }
}
 
Example 18
Source File: DistributionService_Test.java    From estatio with Apache License 2.0 4 votes vote down vote up
@Test
public void generateKeyValuesRoundingBy3DecimalsPositiveDeltaPercent() {

    //given
    DistributionService distributionService = new DistributionService();
    List<Distributable> input = new ArrayList<>();

    //10000.99
    KeyItem item1 = new KeyItem();
    item1.setSourceValue(BigDecimal.valueOf(10000.99));
    input.add(item1);

    //0.99
    KeyItem item2 = new KeyItem();
    item2.setSourceValue(BigDecimal.valueOf(0.99));
    input.add(item2);

    //1.99
    for (int i = 2; i < 14; i = i + 1) {
        KeyItem item = new KeyItem();
        item.setSourceValue(BigDecimal.valueOf(1.99));
        input.add(item);
    }

    //theoretical max rounding error: 14*0.0005 = +/- 0.007
    //in this example here we get to 0.002

    //when
    List<Distributable> output = distributionService.distribute(input, new BigDecimal(100), 3);
    BigDecimal sumRoundedValues = BigDecimal.ZERO;
    for (Distributable object : output) {
        sumRoundedValues = sumRoundedValues.add(object.getValue(), MathContext.DECIMAL64);
    }

    //then

    assertThat(output).hasSize(14);
    assertThat(output.get(0).getValue()).isEqualTo(BigDecimal.valueOf(99.752).setScale(3, BigDecimal.ROUND_HALF_UP));
    assertThat(output.get(1).getValue()).isEqualTo(BigDecimal.valueOf(0.010).setScale(3, BigDecimal.ROUND_HALF_UP));

    for (int i = 2; i < 12; i = i + 1) {
        assertThat(output.get(i).getValue()).isEqualTo(BigDecimal.valueOf(0.020).setScale(3, BigDecimal.ROUND_HALF_UP));
    }

    for (int i = 12; i < 14; i = i + 1) {
        assertThat(output.get(i).getValue()).isEqualTo(BigDecimal.valueOf(0.019).setScale(3, BigDecimal.ROUND_HALF_UP));
    }

    // Corrected Rounding Error for 3 decimals
    assertThat(sumRoundedValues.setScale(3, BigDecimal.ROUND_HALF_UP)).isEqualTo(BigDecimal.valueOf(100.000).setScale(3, BigDecimal.ROUND_HALF_UP));

}
 
Example 19
Source File: Converters.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
@Override
public BigDecimal toBigDecimal(OptimizedElementArray row,
    int columnIndex) throws SQLException {
  return BigDecimal.ZERO;
}
 
Example 20
Source File: InvoiceVatRoundingService.java    From estatio with Apache License 2.0 4 votes vote down vote up
private BigDecimal totalNetAmountFor(final List<InvoiceItemForLease> items) {
    return items.isEmpty() ? BigDecimal.ZERO : items.stream().map(InvoiceItemForLease::getNetAmount).reduce(BigDecimal::add).get();
}