public BigDecimal calculateEntropy(
      Map<Integer, AttributeValue> attributeValues, boolean withVariance) throws MLException {
    if (!withVariance) {
      return calculateEntropy(attributeValues);
    } else {
      BigDecimal attributeEntropyresult = new BigDecimal(0);

      for (AttributeValue attributeValue : attributeValues.values()) {
        int attributeValueCount = attributeValue.getAttributeValueCount();

        BigDecimal innerVarianceResult = new BigDecimal(1);
        for (Integer corrospondingClassifiedCount :
            attributeValue.getClassifiedCountMap().values()) {

          BigDecimal fraction =
              BigDecimal.valueOf(corrospondingClassifiedCount)
                  .divide(new BigDecimal(attributeValueCount), globalMathContext);
          innerVarianceResult.multiply(fraction, globalMathContext);
        }

        attributeValue.setEntropy(innerVarianceResult);
        BigDecimal attributeGlobalFraction =
            BigDecimal.valueOf(attributeValueCount)
                .divide(new BigDecimal(size()), globalMathContext);
        attributeEntropyresult =
            attributeEntropyresult.add(attributeGlobalFraction.multiply(innerVarianceResult));
      }

      return attributeEntropyresult;
    }
  }
  // Gauss-Legendre Algorithm
  public static BigDecimal calculatePi() {
    BigDecimal a = ONE;
    BigDecimal b = ONE.divide(sqrt(TWO, SCALE), SCALE, BigDecimal.ROUND_HALF_UP);
    BigDecimal t = new BigDecimal(0.25);
    BigDecimal x = ONE;
    BigDecimal y;

    while (!a.equals(b)) {
      y = a;

      // a = (a + b)/2
      a = a.add(b).divide(TWO, SCALE, BigDecimal.ROUND_HALF_UP);

      // b = sqrt(b*y)
      b = sqrt(b.multiply(y), SCALE);

      // t -= x*((y - a)^2)
      t = t.subtract(x.multiply(y.subtract(a).multiply(y.subtract(a))));

      // x *= 2
      x = x.multiply(TWO);
    }
    // a + (a+b)/(4)
    return a.add(b).multiply(a.add(b)).divide(t.multiply(FOUR), SCALE, BigDecimal.ROUND_HALF_UP);
  }
Exemplo n.º 3
0
  public static EastNorth getCentroid(List<Node> nodes) {
    // Compute the centroid of nodes

    BigDecimal area = new BigDecimal(0);
    BigDecimal north = new BigDecimal(0);
    BigDecimal east = new BigDecimal(0);

    // See http://en.wikipedia.org/w/index.php?title=Centroid&oldid=294224857#Centroid_of_polygon
    // for the equation used here
    for (int i = 0; i < nodes.size(); i++) {
      EastNorth n0 = nodes.get(i).getEastNorth();
      EastNorth n1 = nodes.get((i + 1) % nodes.size()).getEastNorth();

      BigDecimal x0 = new BigDecimal(n0.east());
      BigDecimal y0 = new BigDecimal(n0.north());
      BigDecimal x1 = new BigDecimal(n1.east());
      BigDecimal y1 = new BigDecimal(n1.north());

      BigDecimal k =
          x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128));

      area = area.add(k, MathContext.DECIMAL128);
      east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128));
      north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128));
    }

    BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3
    area = area.multiply(d, MathContext.DECIMAL128);
    if (area.compareTo(BigDecimal.ZERO) != 0) {
      north = north.divide(area, MathContext.DECIMAL128);
      east = east.divide(area, MathContext.DECIMAL128);
    }

    return new EastNorth(east.doubleValue(), north.doubleValue());
  }
Exemplo n.º 4
0
  @Test
  public void test() {

    Human buyer = new Human();
    Human seller = new Human();

    seller.createConsumable();

    final BigDecimal totalMoney = Money.MoneySupply.getTotalMoney();
    final BigDecimal buyerWorth = buyer.getMonetaryWorth();
    final BigDecimal sellerWorth = seller.getMonetaryWorth();
    final int numSellerConsumables = seller.getNumConsumables();
    final int numBuyerConsumables = buyer.getNumConsumables();

    IConsumable product = seller.getItemsForSale().get(0);
    final int consumableId = product.getId();
    final BigDecimal price = product.getPrice();

    TransactionTerms transactionTerms =
        new TransactionTerms(price.multiply(new BigDecimal(2)), consumableId);
    TransactionAgreement agreement = buyer.proposeTransaction(seller, transactionTerms);

    new Transaction(buyer, seller, agreement);

    final BigDecimal totalMoneyAfterTrans = Money.MoneySupply.getTotalMoney();
    final BigDecimal buyerPostWorth = buyer.getMonetaryWorth();
    final BigDecimal sellerPostWorth = seller.getMonetaryWorth();

    Assert.assertEquals(totalMoney, totalMoneyAfterTrans);
    Assert.assertEquals(buyerWorth.subtract(price.multiply(new BigDecimal(2))), buyerPostWorth);
    Assert.assertEquals(sellerWorth.add(price.multiply(new BigDecimal(2))), sellerPostWorth);
    Assert.assertEquals(numSellerConsumables - 1, seller.getNumConsumables());
    Assert.assertEquals(numBuyerConsumables + 1, buyer.getNumConsumables());
  }
  public static BigDecimal calculateDiscount(
      BigDecimal basePrice, VoucherResponse voucher, BigDecimal unitPrice) {
    Discount discount = voucher.getDiscount();

    if (discount.getType() == DiscountType.PERCENT) {
      validatePercentDiscount(discount);

      return basePrice
          .multiply(valueOf(discount.getPercentOff() / 100.0))
          .setScale(2, RoundingMode.HALF_UP);

    } else if (discount.getType() == DiscountType.AMOUNT) {
      validateAmountDiscount(discount);

      BigDecimal amountOff = valueOf(discount.getAmountOff() / 100.0);
      BigDecimal newPrice = basePrice.subtract(amountOff).setScale(2, RoundingMode.HALF_UP);

      return (newPrice.doubleValue() > 0 ? amountOff : basePrice).setScale(2, RoundingMode.HALF_UP);
    } else if (discount.getType() == DiscountType.UNIT) {
      validateUnitDiscount(discount);

      BigDecimal amountOff = unitPrice.multiply(valueOf(discount.getUnitOff()));
      BigDecimal newPrice = basePrice.subtract(amountOff).setScale(2, RoundingMode.HALF_UP);

      return (newPrice.doubleValue() > 0 ? amountOff : basePrice).setScale(2, RoundingMode.HALF_UP);
    } else {
      throw new RuntimeException("Unknown voucher type");
    }
  }
Exemplo n.º 6
0
  private int start(int rounding, int iterations) {
    BigDecimal three = new BigDecimal("3");
    BigDecimal two = new BigDecimal("2");
    MathContext division = new MathContext((int) Math.round(rounding), RoundingMode.HALF_UP);

    BigDecimal x0 = new BigDecimal("5.0");
    BigDecimal x1 = new BigDecimal("5.0");

    for (int i = 0; i < iterations; i++) {
      /*x1 = x0.pow(2);
      System.out.println("1: " + x1.toPlainString());
      x1 = x1.subtract(three);
      System.out.println("2: " + x1.toPlainString());
      x1 = x1.divide(x0.multiply(two), division);
      System.out.println("3: " + x1.toPlainString());
      x0 = x0.subtract(x1);
      System.out.println("x0: " + x1.toPlainString());*/
      x1 = x0.subtract((x0.pow(2).subtract(three)).divide(x0.multiply(two), division));
      x0 = x1;
      // if(i % 10 == 0) { System.out.println(i); }
    }
    String digits1 = x1.toString();
    x1 = x0.subtract((x0.pow(2).subtract(three)).divide(x0.multiply(two), division));
    x0 = x1;
    String digits2 = x1.toString();

    // System.out.println("Sqrt(3) = " + x1.toPlainString());
    return checkDigits(digits1, digits2);
  }
Exemplo n.º 7
0
  private static BigDecimal getConvertedAmountFromHighToLow(
      AreaEnum sourceType, AreaEnum targetType, BigDecimal amount) {
    BigDecimal updatedAmount = null;
    BigDecimal tmp = SQ_MILE_TO_SQ_KM.multiply(AreaEnum.SQ_YARD.getUpperToLowerVal());

    if (sourceType == targetType) {
      return amount;
    }
    if (isCommonRuleApplicable(sourceType, targetType)) {
      updatedAmount = getCommonConvertedAmountFromHighToLow(sourceType, targetType, amount);
      return updatedAmount.abs(Constant.MC);
    }
    if (sourceType == AreaEnum.SQ_MILE) {
      updatedAmount = amount.multiply(SQ_MILE_TO_SQ_KM);
    } else if (sourceType == AreaEnum.SQ_YARD) {
      updatedAmount = amount.multiply(SQ_YARD_TO_SQ_KM);
    } else if (sourceType == AreaEnum.SQ_FOOT) {
      updatedAmount = amount.multiply(SQ_FT_TO_SQ_KM);
    } else if (sourceType == AreaEnum.SQ_INCH) {
      updatedAmount = amount.multiply(SQ_INCH_TO_SQ_KM);
    }
    updatedAmount =
        getCommonConvertedAmountFromHighToLow(AreaEnum.SQ_KM, targetType, updatedAmount);
    return updatedAmount.abs(Constant.MC);
  }
Exemplo n.º 8
0
 /**
  * Gets common converted amount from low to high.
  *
  * @param sourceType the source type
  * @param targetType the target type
  * @param originalAmount the original amount
  * @param calculatedAmount the calculated amount
  * @return the common converted amount from low to high
  */
 public static BigDecimal getCommonConvertedAmountFromLowToHigh(
     AreaEnum sourceType,
     AreaEnum targetType,
     BigDecimal originalAmount,
     BigDecimal calculatedAmount) {
   if (sourceType == targetType) {
     return calculatedAmount;
   }
   BigDecimal result = BigDecimal.ONE;
   boolean startFlag = false;
   AreaEnum[] vv = AreaEnum.values();
   int len = vv.length - 1;
   for (int i = len; i >= 0; --i) {
     AreaEnum t = vv[i];
     if (sourceType == t && startFlag == false) {
       startFlag = true;
       continue;
     }
     if (startFlag) {
       BigDecimal srcAmountVal = t.getLowerToUpperVal();
       result = result.multiply(srcAmountVal, Constant.MC);
       if (t == targetType) {
         break;
       }
     }
   }
   return calculatedAmount.multiply(result);
 }
  public void adcionarServicoPrestado() {
    ServicoPrestado sp = null;
    boolean tem = false;
    for (ServicoPrestado servicoPrestado : this.tratamento.getServicosPrestados()) {
      if (servicoPrestado.getServico().equals(this.servicoSelecionado)) {
        tem = true;
        sp = servicoPrestado;
      }
    }

    if (tem) {
      BigDecimal valorAnt = sp.getValor();
      Long novaQuant = sp.getQuantidade() + quantidadeServico;
      sp.setQuantidade(novaQuant);
      BigDecimal novoValor = valorSelecionado.multiply(BigDecimal.valueOf(quantidadeServico));
      BigDecimal valorTotal = valorAnt.add(novoValor);
      sp.setValor(valorTotal);
    } else {
      ServicoPrestado servicoPrestado = new ServicoPrestado();
      servicoPrestado.setQuantidade(quantidadeServico);
      BigDecimal valorTotal = valorSelecionado.multiply(BigDecimal.valueOf(quantidadeServico));
      servicoPrestado.setValor(valorTotal);
      servicoPrestado.setServico(servicoSelecionado);
      List<ServicoPrestado> prestados = this.tratamento.getServicosPrestados();
      prestados.add(servicoPrestado);
      this.tratamento.setServicosPrestados(prestados);
    }

    servicoSelecionado = new Servico();
    quantidadeServico = null;
    valorSelecionado = null;
  }
Exemplo n.º 10
0
 /** Calculate Commission */
 public void calculateCommission() {
   MCommissionDetail[] details = getDetails();
   BigDecimal ConvertedAmt = Env.ZERO;
   BigDecimal ActualQty = Env.ZERO;
   for (int i = 0; i < details.length; i++) {
     MCommissionDetail detail = details[i];
     BigDecimal amt = detail.getConvertedAmt();
     if (amt == null) amt = Env.ZERO;
     ConvertedAmt = ConvertedAmt.add(amt);
     ActualQty = ActualQty.add(detail.getActualQty());
   }
   setConvertedAmt(ConvertedAmt);
   setActualQty(ActualQty);
   //
   MCommissionLine cl = new MCommissionLine(getCtx(), getC_CommissionLine_ID(), get_TrxName());
   //	Qty
   BigDecimal qty = getActualQty().subtract(cl.getQtySubtract());
   if (cl.isPositiveOnly() && qty.signum() < 0) qty = Env.ZERO;
   qty = qty.multiply(cl.getQtyMultiplier());
   //	Amt
   BigDecimal amt = getConvertedAmt().subtract(cl.getAmtSubtract());
   if (cl.isPositiveOnly() && amt.signum() < 0) amt = Env.ZERO;
   amt = amt.multiply(cl.getAmtMultiplier());
   //
   setCommissionAmt(amt.add(qty));
 } //	calculateCommission
Exemplo n.º 11
0
  /**
   * JournalLine - Amt. Convert the source amount to accounted amount (AmtAcctDr/Cr) Called when
   * source amount (AmtSourceCr/Dr) or rate changes
   *
   * @param ctx context
   * @param WindowNo window no
   * @param mTab tab
   * @param mField field
   * @param value value
   * @return null or error message
   */
  public String amt(Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value) {
    String colName = mField.getColumnName();
    if (value == null || isCalloutActive()) return "";

    //  Get Target Currency & Precision from C_AcctSchema.C_Currency_ID
    int C_AcctSchema_ID = Env.getContextAsInt(ctx, WindowNo, "C_AcctSchema_ID");
    MAcctSchema as = MAcctSchema.get(ctx, C_AcctSchema_ID);
    int Precision = as.getStdPrecision();

    BigDecimal CurrencyRate = (BigDecimal) mTab.getValue("CurrencyRate");
    if (CurrencyRate == null) {
      CurrencyRate = Env.ONE;
      mTab.setValue("CurrencyRate", CurrencyRate);
    }

    //  AmtAcct = AmtSource * CurrencyRate  ==> Precision
    BigDecimal AmtSourceDr = (BigDecimal) mTab.getValue("AmtSourceDr");
    if (AmtSourceDr == null) AmtSourceDr = Env.ZERO;
    BigDecimal AmtSourceCr = (BigDecimal) mTab.getValue("AmtSourceCr");
    if (AmtSourceCr == null) AmtSourceCr = Env.ZERO;

    BigDecimal AmtAcctDr = AmtSourceDr.multiply(CurrencyRate);
    AmtAcctDr = AmtAcctDr.setScale(Precision, BigDecimal.ROUND_HALF_UP);
    mTab.setValue("AmtAcctDr", AmtAcctDr);
    BigDecimal AmtAcctCr = AmtSourceCr.multiply(CurrencyRate);
    AmtAcctCr = AmtAcctCr.setScale(Precision, BigDecimal.ROUND_HALF_UP);
    mTab.setValue("AmtAcctCr", AmtAcctCr);

    return "";
  } //  amt
  /**
   * Parent Constructor
   *
   * @param invoice invoice
   * @param paySchedule payment schedule
   */
  public MInvoicePaySchedule(MInvoice invoice, MPaySchedule paySchedule) {
    super(invoice.getCtx(), 0, invoice.get_TrxName());
    m_parent = invoice;
    setClientOrg(invoice);
    setC_Invoice_ID(invoice.getC_Invoice_ID());
    setC_PaySchedule_ID(paySchedule.getC_PaySchedule_ID());

    //	Amounts
    int scale = MCurrency.getStdPrecision(getCtx(), invoice.getC_Currency_ID());
    BigDecimal due = invoice.getGrandTotal();
    if (due.compareTo(Env.ZERO) == 0) {
      setDueAmt(Env.ZERO);
      setDiscountAmt(Env.ZERO);
      setIsValid(false);
    } else {
      due =
          due.multiply(paySchedule.getPercentage())
              .divide(HUNDRED, scale, BigDecimal.ROUND_HALF_UP);
      setDueAmt(due);
      BigDecimal discount =
          due.multiply(paySchedule.getDiscount()).divide(HUNDRED, scale, BigDecimal.ROUND_HALF_UP);
      setDiscountAmt(discount);
      setIsValid(true);
    }

    //	Dates
    Timestamp dueDate = TimeUtil.addDays(invoice.getDateInvoiced(), paySchedule.getNetDays());
    setDueDate(dueDate);
    Timestamp discountDate =
        TimeUtil.addDays(invoice.getDateInvoiced(), paySchedule.getDiscountDays());
    setDiscountDate(discountDate);
  } //	MInvoicePaySchedule
Exemplo n.º 13
0
  public BigDecimal calculateEntropy(Map<Integer, AttributeValue> attributeValues)
      throws MLException {
    BigDecimal attributeEntropyresult = new BigDecimal(0);

    for (AttributeValue attributeValue : attributeValues.values()) {
      int attributeCount = attributeValue.getAttributeValueCount();

      BigDecimal innerResult = new BigDecimal(0);
      for (Integer corrospondingClassifiedCount : attributeValue.getClassifiedCountMap().values()) {

        BigDecimal fraction =
            BigDecimal.valueOf(corrospondingClassifiedCount)
                .divide(new BigDecimal(attributeCount), globalMathContext);
        BigDecimal logFraction =
            BigDecimal.valueOf(Math.log(fraction.doubleValue()))
                .divide(new BigDecimal(Math.log(2)), globalMathContext);

        innerResult = innerResult.add(fraction.multiply(logFraction, globalMathContext));
      }
      innerResult = innerResult.negate();
      attributeValue.setEntropy(innerResult);

      BigDecimal attributeGlobalFraction =
          BigDecimal.valueOf(attributeValue.getAttributeValueCount())
              .divide(new BigDecimal(size()), globalMathContext);

      attributeEntropyresult =
          attributeEntropyresult.add(attributeGlobalFraction.multiply(innerResult));
    }

    return attributeEntropyresult;
  }
Exemplo n.º 14
0
  @Override
  public void Zoom(BigDecimal Percent, Point2D Center) {
    CurrentZoom = Percent;

    // distance between first point and center
    BigDecimal X1Distance = new BigDecimal(Double.toString(Center.getX())).subtract(X1);
    BigDecimal Y1Distance = new BigDecimal(Double.toString(Center.getY())).subtract(Y1);
    // distance between second point and center
    BigDecimal X2Distance = new BigDecimal(Double.toString(Center.getX())).subtract(X2);
    BigDecimal Y2Distance = new BigDecimal(Double.toString(Center.getY())).subtract(Y2);

    X1Distance = X1Distance.multiply(Percent);
    Y1Distance = Y1Distance.multiply(Percent);
    X2Distance = X2Distance.multiply(Percent);
    Y2Distance = Y2Distance.multiply(Percent);

    X1New = new BigDecimal(Double.toString(Center.getX())).subtract(X1Distance);
    Y1New = new BigDecimal(Double.toString(Center.getY())).subtract(Y1Distance);
    X2New = new BigDecimal(Double.toString(Center.getX())).subtract(X2Distance);
    Y2New = new BigDecimal(Double.toString(Center.getY())).subtract(Y2Distance);

    MainLine =
        new Line2D.Double(
            X1New.doubleValue(), Y1New.doubleValue(), X2New.doubleValue(), Y2New.doubleValue());
  }
Exemplo n.º 15
0
 private BigDecimal calculateAveragePrice(
     String companyName, Integer numberOfStock, BigDecimal purchasePrice) {
   Integer currentStocks = stock.get(companyName);
   BigDecimal currentPurchasePrice = purchasePrices.get(companyName);
   return ((currentPurchasePrice.multiply(new BigDecimal(currentStocks)))
           .add(purchasePrice.multiply(new BigDecimal(numberOfStock))))
       .divide(new BigDecimal(numberOfStock + currentStocks), 2, BigDecimal.ROUND_DOWN);
 }
  public static void invoke(
      final BigDecimal[] aData, final Householder.Big aHouseholder, final BigDecimal[] aWorker) {

    final BigDecimal[] tmpVector = aHouseholder.vector;
    final int tmpFirst = aHouseholder.first;
    final int tmpLength = tmpVector.length;
    final BigDecimal tmpBeta = aHouseholder.beta;
    final int tmpCount = tmpLength - tmpFirst;

    if (tmpCount > THRESHOLD) {

      final DivideAndConquer tmpConqurer =
          new DivideAndConquer() {

            @Override
            protected void conquer(final int aFirst, final int aLimit) {
              MultiplyHermitianAndVector.invoke(
                  aWorker, aFirst, aLimit, aData, tmpVector, tmpFirst);
            }
          };

      tmpConqurer.invoke(tmpFirst, tmpLength, THRESHOLD);

    } else {

      MultiplyHermitianAndVector.invoke(aWorker, tmpFirst, tmpLength, aData, tmpVector, tmpFirst);
    }

    BigDecimal tmpVal = BigMath.ZERO;
    for (int c = tmpFirst; c < tmpLength; c++) {
      // tmpVal += tmpVector[c] * aWorker[c];
      tmpVal = tmpVal.add(tmpVector[c].multiply(aWorker[c]));
    }
    // tmpVal *= (tmpBeta / TWO);
    tmpVal = BigFunction.DIVIDE.invoke(tmpVal.multiply(tmpBeta), BigMath.TWO);
    for (int c = tmpFirst; c < tmpLength; c++) {
      // aWorker[c] = tmpBeta * (aWorker[c] - (tmpVal * tmpVector[c]));
      aWorker[c] = tmpBeta.multiply(aWorker[c].subtract(tmpVal.multiply(tmpVector[c])));
    }

    if (tmpCount > THRESHOLD) {

      final DivideAndConquer tmpConqurer =
          new DivideAndConquer() {

            @Override
            protected void conquer(final int aFirst, final int aLimit) {
              HermitianRank2Update.invoke(aData, aFirst, aLimit, tmpVector, aWorker);
            }
          };

      tmpConqurer.invoke(tmpFirst, tmpLength, THRESHOLD);

    } else {

      HermitianRank2Update.invoke(aData, tmpFirst, tmpLength, tmpVector, aWorker);
    }
  }
Exemplo n.º 17
0
public abstract class BigMath {

  public static final BigDecimal ZERO = new BigDecimal("0", MathContext.DECIMAL128);
  public static final BigDecimal ONE = new BigDecimal("1", MathContext.DECIMAL128);
  public static final BigDecimal TWO = new BigDecimal("2", MathContext.DECIMAL128);
  public static final BigDecimal THREE = new BigDecimal("3", MathContext.DECIMAL128);
  public static final BigDecimal FOUR = new BigDecimal("4", MathContext.DECIMAL128);
  public static final BigDecimal FIVE = new BigDecimal("5", MathContext.DECIMAL128);
  public static final BigDecimal SIX = new BigDecimal("6", MathContext.DECIMAL128);
  public static final BigDecimal SEVEN = new BigDecimal("7", MathContext.DECIMAL128);
  public static final BigDecimal EIGHT = new BigDecimal("8", MathContext.DECIMAL128);
  public static final BigDecimal NINE = new BigDecimal("9", MathContext.DECIMAL128);
  public static final BigDecimal TEN = new BigDecimal("10", MathContext.DECIMAL128);
  public static final BigDecimal ELEVEN = new BigDecimal("11", MathContext.DECIMAL128);
  public static final BigDecimal TWELVE = new BigDecimal("12", MathContext.DECIMAL128);
  public static final BigDecimal HUNDRED = new BigDecimal("100", MathContext.DECIMAL128);
  public static final BigDecimal THOUSAND = new BigDecimal("1000", MathContext.DECIMAL128);

  public static final BigDecimal NEG = ONE.negate();

  public static final BigDecimal HALF = ONE.divide(TWO, MathContext.DECIMAL128);
  public static final BigDecimal THIRD = ONE.divide(THREE, MathContext.DECIMAL128);
  public static final BigDecimal QUARTER = ONE.divide(FOUR, MathContext.DECIMAL128);
  public static final BigDecimal FITH = ONE.divide(FIVE, MathContext.DECIMAL128);
  public static final BigDecimal SIXTH = ONE.divide(SIX, MathContext.DECIMAL128);
  public static final BigDecimal SEVENTH = ONE.divide(SEVEN, MathContext.DECIMAL128);
  public static final BigDecimal EIGHTH = ONE.divide(EIGHT, MathContext.DECIMAL128);
  public static final BigDecimal NINTH = ONE.divide(NINE, MathContext.DECIMAL128);
  public static final BigDecimal TENTH = ONE.divide(TEN, MathContext.DECIMAL128);
  public static final BigDecimal ELEVENTH = ONE.divide(ELEVEN, MathContext.DECIMAL128);
  public static final BigDecimal TWELFTH = ONE.divide(TWELVE, MathContext.DECIMAL128);
  public static final BigDecimal HUNDREDTH = ONE.divide(HUNDRED, MathContext.DECIMAL128);
  public static final BigDecimal THOUSANDTH = ONE.divide(THOUSAND, MathContext.DECIMAL128);

  public static final BigDecimal E =
      new BigDecimal(
          "2.71828182845904523536028747135266249775724709369996", MathContext.DECIMAL128);
  public static final BigDecimal PI =
      new BigDecimal(
          "3.14159265358979323846264338327950288419716939937511", MathContext.DECIMAL128);

  public static final BigDecimal HALF_PI = HALF.multiply(PI, MathContext.DECIMAL128);
  public static final BigDecimal TWO_PI = TWO.multiply(PI, MathContext.DECIMAL128);

  public static final BigDecimal SQRT_TWO = BigFunction.SQRT.invoke(TWO);
  public static final BigDecimal SQRT_PI = BigFunction.SQRT.invoke(PI);
  public static final BigDecimal SQRT_TWO_PI = BigFunction.SQRT.invoke(TWO.multiply(PI));

  public static final BigDecimal VERY_NEGATIVE =
      new BigDecimal(Long.MIN_VALUE, MathContext.DECIMAL128);
  public static final BigDecimal VERY_POSITIVE =
      new BigDecimal(Long.MAX_VALUE, MathContext.DECIMAL128);

  private BigMath() {
    super();
  }
}
Exemplo n.º 18
0
  @Override
  public BigDecimal calcular(final BigDecimal x) {
    BigDecimal value = null;

    value = a.multiply(x.multiply(x));
    value = value.add(b.multiply(x));
    value = value.add(c);

    return value;
  }
Exemplo n.º 19
0
 /**
  * Calculate Grade Factor. Checked against "Introduction to the Scheduler Log" white paper
  *
  * @param schedule
  * @return Grade factor for the schedule
  */
 public BigDecimal calcGrade(ScheduleWrapper schedule) {
   // 1 - gradeFactor*(1 - rawGradeFactor)
   BigDecimal sum = new BigDecimal(0, MathContext.DECIMAL32);
   for (Iterator<Job> it = schedule.getJobs().iterator(); it.hasNext(); ) {
     Job job = it.next();
     Integer iLevel = schedule.getSkillLevel(job.getSkillTypeRef().getId());
     if (iLevel == null) {
       // FIXME: If a job is put on the work schedule, and then the skill for that job is deleted
       // from the worker,
       // schedule.getSkillLevel will return null. The job is no longer valid for the work
       // schedule, and should
       // be removed. There are two places that this removal should occur:
       // 1. When the user deletes a skill from a worker, a check should be made to see if any jobs
       // on the worker's
       //    current schedule have that skill. The user can then decide to abort, or delete the
       // skill and remove
       //    the jobs from the schedule.
       // 2. When data is being prepared for the Scheduler, the data should be examined to see if
       // the person's skills
       //    match the jobs on the schedules for that person, and remove any jobs which require
       // skills the person
       //    does not have.
       //
       //  i.e. the fix for invalid data should not be done here. This code just catches the cases
       // where the data clean
       //  was not performed prior to calling this code.
       //
       log(
           "Worker does not have skill '"
               + job.getSkillTypeRef().getDescription()
               + "', though job "
               + job.getId()
               + " requires it.");
       continue;
     }
     int schedSkillLevel = iLevel;
     // # grades worker skill level is over job skill level
     BigDecimal over =
         new BigDecimal(
             schedSkillLevel - job.getSkillLevelRef().getValue(), MathContext.DECIMAL32);
     // 1 - (over/maxGrade)
     BigDecimal penalty =
         new BigDecimal(1).subtract(over.divide(new BigDecimal(maxGrade), MathContext.DECIMAL32));
     BigDecimal ptime = new BigDecimal(job.getEstimatedTime().intValue(), MathContext.DECIMAL32);
     BigDecimal ptimepenalty = ptime.multiply(penalty);
     sum = sum.add(ptimepenalty);
   }
   BigDecimal prodTime =
       new BigDecimal(schedule.getProductiveTime(), MathContext.DECIMAL32).multiply(ONEHUNDRED);
   // sum/(scheduleProdTime Hundredths)
   BigDecimal rawGradeFactor = sum.divide(prodTime, MathContext.DECIMAL32);
   BigDecimal oneMinusRawGrade = new BigDecimal(1).subtract(rawGradeFactor);
   BigDecimal result = new BigDecimal(1).subtract(gradeFactor.multiply(oneMinusRawGrade));
   return result;
 }
Exemplo n.º 20
0
  public void totalCalculation() {
    BigDecimal totalPurchaseACC = BigDecimal.ZERO;
    BigDecimal totalPurchaseAAP = BigDecimal.ZERO;
    BigDecimal totalDiscACC = BigDecimal.ZERO;
    BigDecimal totalDiscAAP = BigDecimal.ZERO;
    BigDecimal vsACC = BigDecimal.ZERO;
    BigDecimal vsAAP = BigDecimal.ZERO;

    for (int i = 0; i < xTableACC.getRowCount(); i++) {
      totalPurchaseACC = totalPurchaseACC.add((BigDecimal) xTableACC.getValueAt(i, 6));
      totalDiscACC = totalDiscACC.add((BigDecimal) xTableACC.getValueAt(i, 7));
    }

    for (int i = 0; i < xTableAAP.getRowCount(); i++) {
      totalPurchaseAAP = totalPurchaseAAP.add((BigDecimal) xTableAAP.getValueAt(i, 5));
      totalDiscAAP = totalDiscAAP.add((BigDecimal) xTableAAP.getValueAt(i, 6));
    }
    if (totalPurchaseACC != BigDecimal.ZERO)
      vsACC =
          totalDiscACC
              .multiply(new BigDecimal(100))
              .divide(totalPurchaseACC, 2, RoundingMode.HALF_UP);
    if (totalPurchaseAAP != BigDecimal.ZERO)
      vsAAP =
          totalDiscAAP
              .multiply(new BigDecimal(100))
              .divide(totalPurchaseAAP, 2, RoundingMode.HALF_UP);
    this.totalPurchaseACC.setText(
        header1
            + totalPurchaseACC
            + "   "
            + header2
            + totalDiscACC
            + "   "
            + header3
            + "   "
            + vsACC
            + "</PRE></font>"
            + "</html>");

    this.totalPurchaseAAP.setText(
        header1
            + totalPurchaseAAP
            + "   "
            + header2
            + "   "
            + totalDiscAAP
            + "   "
            + header3
            + "   "
            + vsAAP
            + "</PRE></font>"
            + "</html>");
  }
Exemplo n.º 21
0
 public static Long getSatoshis(BigDecimal fiatValue, Double oneBtcInFiat) {
   if (fiatValue == null || oneBtcInFiat == null) {
     return null;
   }
   BigDecimal fiatCents = fiatValue.multiply(ONE_HUNDRED);
   BigDecimal oneBtcInFiatCents = BigDecimal.valueOf(oneBtcInFiat).multiply(ONE_HUNDRED);
   return fiatCents
       .multiply(BTC_IN_SATOSHIS)
       .divide(oneBtcInFiatCents, 0, RoundingMode.HALF_UP)
       .longValue();
 }
 private BigDecimal calcularDividendo() {
   // Dos apuestas de MONTO_APUESTA donde solo 1 es acertada.
   BigDecimal montoApostado = MONTO_APUESTA.multiply(new BigDecimal(2));
   BigDecimal porcentajeARepartir =
       BigDecimal.ONE.subtract(BolsasApuestasManager.porcentajeComisionHipodromo);
   BigDecimal totalARepartir = montoApostado.multiply(porcentajeARepartir);
   BigDecimal dividendo = totalARepartir.divide(MONTO_APUESTA, 2, BigDecimal.ROUND_CEILING);
   if (BigDecimal.ONE.compareTo(dividendo) > 0) {
     dividendo = BigDecimal.ONE.setScale(2);
   }
   return dividendo;
 }
Exemplo n.º 23
0
 public static BigDecimal sqrt(BigDecimal b) {
   BigDecimal half = new BigDecimal(1d / 2d);
   BigDecimal value = b;
   BigDecimal precision = new BigDecimal(10e-150);
   while (value
           .subtract(b.divide(value, 300, RoundingMode.HALF_UP))
           .compareTo(precision.multiply(value))
       > 0) {
     value = half.multiply(value.add(b.divide(value, 300, RoundingMode.HALF_UP)));
   }
   return value;
 }
Exemplo n.º 24
0
  /*
   * Returns the value of a given ShipmentPackageContent record.  Calculated by working out the total value (from the OrderItems) of all ItemIssuances
   * for the ShipmentItem then dividing that by the total quantity issued for the same to get an average item value then multiplying that by the package
   * content quantity.
   * Note: No rounding of the calculation is performed so you will need to round it to the accuracy that you require
   */
  public static BigDecimal getShipmentPackageContentValue(GenericValue shipmentPackageContent) {
    BigDecimal quantity = shipmentPackageContent.getBigDecimal("quantity");

    BigDecimal value = new BigDecimal("0");

    // lookup the issuance to find the order
    List<GenericValue> issuances = null;
    try {
      GenericValue shipmentItem = shipmentPackageContent.getRelatedOne("ShipmentItem");
      issuances = shipmentItem.getRelated("ItemIssuance");
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }

    BigDecimal totalIssued = BigDecimal.ZERO;
    BigDecimal totalValue = BigDecimal.ZERO;
    if (UtilValidate.isNotEmpty(issuances)) {
      for (GenericValue issuance : issuances) {
        // we only need one
        BigDecimal issuanceQuantity = issuance.getBigDecimal("quantity");
        BigDecimal issuanceCancelQuantity = issuance.getBigDecimal("cancelQuantity");
        if (issuanceCancelQuantity != null) {
          issuanceQuantity = issuanceQuantity.subtract(issuanceCancelQuantity);
        }
        // get the order item
        GenericValue orderItem = null;
        try {
          orderItem = issuance.getRelatedOne("OrderItem");
        } catch (GenericEntityException e) {
          Debug.logError(e, module);
        }

        if (orderItem != null) {
          // get the value per unit - (base price * amount)
          BigDecimal selectedAmount = orderItem.getBigDecimal("selectedAmount");
          if (selectedAmount == null || selectedAmount.compareTo(BigDecimal.ZERO) <= 0) {
            selectedAmount = BigDecimal.ONE;
          }

          BigDecimal unitPrice = orderItem.getBigDecimal("unitPrice");
          BigDecimal itemValue = unitPrice.multiply(selectedAmount);

          // total value for package (per unit * quantity)
          totalIssued = totalIssued.add(issuanceQuantity);
          totalValue = totalValue.add(itemValue.multiply(issuanceQuantity));
        }
      }
    }
    // take the average value of the issuances and multiply it by the shipment package content
    // quantity
    value = totalValue.divide(totalIssued, 10, BigDecimal.ROUND_HALF_EVEN).multiply(quantity);
    return value;
  }
Exemplo n.º 25
0
  public PercentType[] toRGB() {
    PercentType red = null;
    PercentType green = null;
    PercentType blue = null;

    BigDecimal h = hue.divide(new BigDecimal(100), 10, BigDecimal.ROUND_HALF_UP);
    BigDecimal s = saturation.divide(new BigDecimal(100));

    int h_int =
        h.multiply(new BigDecimal(5))
            .divide(new BigDecimal(3), 10, BigDecimal.ROUND_HALF_UP)
            .intValue();
    BigDecimal f =
        h.multiply(new BigDecimal(5))
            .divide(new BigDecimal(3), 10, BigDecimal.ROUND_HALF_UP)
            .remainder(BigDecimal.ONE);
    PercentType a = new PercentType(value.multiply(BigDecimal.ONE.subtract(s)));
    PercentType b = new PercentType(value.multiply(BigDecimal.ONE.subtract(s.multiply(f))));
    PercentType c =
        new PercentType(
            value.multiply(BigDecimal.ONE.subtract((BigDecimal.ONE.subtract(f)).multiply(s))));

    if (h_int == 0 || h_int == 6) {
      red = getBrightness();
      green = c;
      blue = a;
    } else if (h_int == 1) {
      red = b;
      green = getBrightness();
      blue = a;
    } else if (h_int == 2) {
      red = a;
      green = getBrightness();
      blue = c;
    } else if (h_int == 3) {
      red = a;
      green = b;
      blue = getBrightness();
    } else if (h_int == 4) {
      red = c;
      green = a;
      blue = getBrightness();
    } else if (h_int == 5) {
      red = getBrightness();
      green = a;
      blue = b;
    } else {
      throw new RuntimeException();
    }
    return new PercentType[] {red, green, blue};
  }
Exemplo n.º 26
0
 /**
  * Calculate Raw Utility. Checked against "Introduction to the Scheduler Log" white paper
  *
  * @param schedule
  * @return Raw Utility
  */
 public BigDecimal rawUtility(ScheduleWrapper schedule) {
   // A is % time on schedule, or used time
   // B is % time * priority, or priority time
   // kValue*A + (1 - kValue)*B
   BigDecimal A = usedTime(schedule);
   if (A.compareTo(BigDecimal.ONE) > 0) A = BigDecimal.ONE;
   BigDecimal B = priorityTime(schedule);
   if (B.compareTo(BigDecimal.ONE) > 0) {
     return new BigDecimal(-1);
   }
   BigDecimal oneMinusKValue = new BigDecimal(1, MathContext.DECIMAL32).subtract(kValue);
   BigDecimal result = kValue.multiply(A).add(oneMinusKValue.multiply(B));
   return result;
 }
Exemplo n.º 27
0
 public static void main(String[] args) {
   BigDecimal f1 = new BigDecimal("0.05");
   BigDecimal f2 = BigDecimal.valueOf(0.01);
   BigDecimal f3 = new BigDecimal(0.05);
   System.out.println("使用String作为BigDecimal构造器参数:");
   System.out.println("0.05 + 0.01 = " + f1.add(f2));
   System.out.println("0.05 - 0.01 = " + f1.subtract(f2));
   System.out.println("0.05 * 0.01 = " + f1.multiply(f2));
   System.out.println("0.05 / 0.01 = " + f1.divide(f2));
   System.out.println("使用double作为BigDecimal构造器参数:");
   System.out.println("0.05 + 0.01 = " + f3.add(f2));
   System.out.println("0.05 - 0.01 = " + f3.subtract(f2));
   System.out.println("0.05 * 0.01 = " + f3.multiply(f2));
   System.out.println("0.05 / 0.01 = " + f3.divide(f2));
 }
Exemplo n.º 28
0
  public static BigDecimal get(final BigDecimal n) {

    // Make sure n is a positive number

    if (n.compareTo(ZERO) <= 0) {
      throw new IllegalArgumentException();
    }

    final BigDecimal initialGuess = getInitialApproximation(n);
    BigDecimal lastGuess = ZERO;
    BigDecimal guess = new BigDecimal(initialGuess.toString());

    // Iterate

    iterations = 0;
    boolean more = true;
    while (more) {
      lastGuess = guess;
      guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP);
      guess = guess.add(lastGuess);
      guess = guess.divide(TWO, scale, BigDecimal.ROUND_HALF_UP);
      error = n.subtract(guess.multiply(guess));
      if (++iterations >= maxIterations) {
        more = false;
      } else if (lastGuess.equals(guess)) {
        more = error.abs().compareTo(ONE) >= 0;
      }
    }
    return guess;
  }
Exemplo n.º 29
0
 private static JsonValue decimalEval(JsonNumber v1, JsonNumber v2, int op) {
   BigDecimal n1 = v1.decimalValue();
   BigDecimal n2 = v2.decimalValue();
   BigDecimal n3;
   switch (op) {
     case PLUS:
       {
         n3 = n1.add(n2, MathContext.DECIMAL128);
         break;
       }
     case MINUS:
       {
         n3 = n1.subtract(n2, MathContext.DECIMAL128);
         break;
       }
     case MULTIPLY:
       {
         n3 = n1.multiply(n2, MathContext.DECIMAL128);
         break;
       }
     case DIVIDE:
       {
         try {
           n3 = n1.divide(n2, MathContext.DECIMAL128);
         } catch (ArithmeticException e) {
           // TODO: need +INF, -INF, and NaN
           return null;
         }
         break;
       }
     default:
       throw new RuntimeException("invalid op:" + op);
   }
   return new JsonDecimal(n3);
 }
Exemplo n.º 30
0
 /**
  * Parse a String size to Bytes.
  *
  * @param spaceSize the size of a space, e.g. 10GB, 5TB, 1024
  * @return the space size in bytes
  */
 public static long parseSpaceSize(String spaceSize) {
   double alpha = 0.0001;
   String ori = spaceSize;
   String end = "";
   int tIndex = spaceSize.length() - 1;
   while (tIndex >= 0) {
     if (spaceSize.charAt(tIndex) > '9' || spaceSize.charAt(tIndex) < '0') {
       end = spaceSize.charAt(tIndex) + end;
     } else {
       break;
     }
     tIndex--;
   }
   spaceSize = spaceSize.substring(0, tIndex + 1);
   double ret = Double.parseDouble(spaceSize);
   end = end.toLowerCase();
   if (end.isEmpty() || end.equals("b")) {
     return (long) (ret + alpha);
   } else if (end.equals("kb")) {
     return (long) (ret * Constants.KB + alpha);
   } else if (end.equals("mb")) {
     return (long) (ret * Constants.MB + alpha);
   } else if (end.equals("gb")) {
     return (long) (ret * Constants.GB + alpha);
   } else if (end.equals("tb")) {
     return (long) (ret * Constants.TB + alpha);
   } else if (end.equals("pb")) {
     // When parsing petabyte values, we can't multiply with doubles and longs, since that will
     // lose presicion with such high numbers. Therefore we use a BigDecimal.
     BigDecimal pBDecimal = new BigDecimal(Constants.PB);
     return pBDecimal.multiply(BigDecimal.valueOf(ret)).longValue();
   } else {
     throw new IllegalArgumentException("Fail to parse " + ori + " to bytes");
   }
 }