Java Code Examples for java.math.BigDecimal#ZERO

The following examples show how to use java.math.BigDecimal#ZERO . 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: nd4j   File: BigDecimalMath.java    License: 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
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 3
Source Project: JavaMainRepo   File: Functions.java    License: 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 4
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 5
Source Project: JavaMainRepo   File: MatrixOperations.java    License: 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 6
Source Project: development   File: Supplier.java    License: 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 7
Source Project: twister2   File: Timing.java    License: 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 8
Source Project: Bats   File: RexBuilder.java    License: 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 9
Source Project: alpha-wallet-android   File: TokenRepository.java    License: 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 10
Source Project: estatio   File: Project_InvoicedAmount.java    License: 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 Project: robozonky   File: SellRequest.java    License: 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 Project: dble   File: ItemFuncMinus.java    License: 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
public BigDecimal getAverage() {
    if (quantity > 0) {
        return sum.divide(new BigDecimal(quantity), RoundingMode.HALF_EVEN);
    } else {
        return BigDecimal.ZERO;
    }

}
 
Example 14
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 Project: streamsx.topology   File: Bargain.java    License: 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
/**
 * 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
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
private BigDecimal totalNetAmountFor(final List<InvoiceItemForLease> items) {
    return items.isEmpty() ? BigDecimal.ZERO : items.stream().map(InvoiceItemForLease::getNetAmount).reduce(BigDecimal::add).get();
}
 
Example 19
@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 20
Source Project: gemfirexd-oss   File: Converters.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public BigDecimal toBigDecimal(OptimizedElementArray row,
    int columnIndex) throws SQLException {
  return BigDecimal.ZERO;
}