@Override
  public BigDecimal getCurrencyValue(CurrencyForm currencyForm) throws NoCurrenciesException {
    Criteria fromCriteria =
        Criteria.where("timestamp")
            .is(currencyForm.getTimestamp())
            .and("currencyCode")
            .is(currencyForm.getFromCurrencyCode());

    List<MongoCurrency> fromCurrencies = currencyMongoDao.query(fromCriteria);

    Criteria toCriteria =
        Criteria.where("timestamp")
            .is(currencyForm.getTimestamp())
            .and("currencyCode")
            .is(currencyForm.getToCurrencyCode());

    List<MongoCurrency> toCurrencies = currencyMongoDao.query(toCriteria);

    if (fromCurrencies.isEmpty() || toCurrencies.isEmpty()) {
      throw new NoCurrenciesException(
          currencyForm.getFromCurrencyCode(),
          currencyForm.getToCurrencyCode(),
          currencyForm.getTimestamp());
    }

    MongoCurrency fromCurrency = fromCurrencies.get(0);
    MongoCurrency toCurrency = toCurrencies.get(0);

    BigDecimal fromCurrencyInUsd =
        BigDecimal.ONE
            .divide(fromCurrency.getValue(), 10, BigDecimal.ROUND_HALF_UP)
            .multiply(currencyForm.getAmountFrom());

    return fromCurrencyInUsd.multiply(toCurrency.getValue());
  }
Exemplo n.º 2
0
  @Override
  public DecimalAmount invert() {

    return bd.compareTo(BigDecimal.ZERO) == 0
        ? new DecimalAmount(BigDecimal.ZERO)
        : new DecimalAmount(BigDecimal.ONE.divide(bd, mc));
  }
Exemplo n.º 3
0
  public static List<Map<String, BigDecimal>> getPackageSplit(
      DispatchContext dctx, List<Map<String, Object>> shippableItemInfo, BigDecimal maxWeight) {
    // create the package list w/ the first package
    List<Map<String, BigDecimal>> packages = FastList.newInstance();

    if (UtilValidate.isNotEmpty(shippableItemInfo)) {
      for (Map<String, Object> itemInfo : shippableItemInfo) {
        long pieces = ((Long) itemInfo.get("piecesIncluded")).longValue();
        BigDecimal totalQuantity = (BigDecimal) itemInfo.get("quantity");
        BigDecimal totalWeight = (BigDecimal) itemInfo.get("weight");
        String productId = (String) itemInfo.get("productId");

        // sanity check
        if (pieces < 1) {
          pieces = 1; // can NEVER be less than one
        }
        BigDecimal weight = totalWeight.divide(BigDecimal.valueOf(pieces), generalRounding);
        for (int z = 1; z <= totalQuantity.intValue(); z++) {
          BigDecimal partialQty =
              pieces > 1
                  ? BigDecimal.ONE.divide(BigDecimal.valueOf(pieces), generalRounding)
                  : BigDecimal.ONE;
          for (long x = 0; x < pieces; x++) {
            if (weight.compareTo(maxWeight) >= 0) {
              Map<String, BigDecimal> newPackage = FastMap.newInstance();
              newPackage.put(productId, partialQty);
              packages.add(newPackage);
            } else if (totalWeight.compareTo(BigDecimal.ZERO) > 0) {
              // create the first package
              if (packages.size() == 0) {
                packages.add(FastMap.<String, BigDecimal>newInstance());
              }

              // package loop
              boolean addedToPackage = false;
              for (Map<String, BigDecimal> packageMap : packages) {
                if (!addedToPackage) {
                  BigDecimal packageWeight =
                      calcPackageWeight(dctx, packageMap, shippableItemInfo, weight);
                  if (packageWeight.compareTo(maxWeight) <= 0) {
                    BigDecimal qty = packageMap.get(productId);
                    qty = UtilValidate.isEmpty(qty) ? BigDecimal.ZERO : qty;
                    packageMap.put(productId, qty.add(partialQty));
                    addedToPackage = true;
                  }
                }
              }
              if (!addedToPackage) {
                Map<String, BigDecimal> packageMap = FastMap.newInstance();
                packageMap.put(productId, partialQty);
                packages.add(packageMap);
              }
            }
          }
        }
      }
    }
    return packages;
  }
Exemplo n.º 4
0
 /**
  * Calculates the value of the first argument raised to the power of the second argument.
  *
  * @param base the base
  * @param expornent the exponent
  * @return the value <tt>a<sup>b</sup></tt> in <tt>BigDecimal</tt>
  */
 private BigDecimal pow(double base, int expornent) {
   BigDecimal value;
   if (expornent > 0) {
     value = new BigDecimal(new Double(base).toString()).pow(expornent);
   } else {
     value = BigDecimal.ONE.divide(new BigDecimal(new Double(base).toString()).pow(-expornent));
   }
   return value;
 }
Exemplo n.º 5
0
 /**
  * Normalize the vector so its L2 Norm is 1 WARNING: This function uses norm() which loses the
  * BigDecimal precision and range in VectorType
  *
  * @param v vector to compute norm of
  * @return normalized input vector
  * @throws ZeroNormException if norm(v) less than Double.MIN_VALUE
  */
 public static VectorType normalize(VectorType v) {
   VectorType vout = new VectorType();
   double normv = norm(v);
   if (normv < Double.MIN_VALUE) {
     throw new ZeroNormException("Can't normalize vector with zero magnitude.");
   }
   BigDecimal normInv = BigDecimal.ONE.divide(BigDecimal.valueOf(norm(v)));
   vout.setI(v.getI().multiply(normInv));
   vout.setJ(v.getJ().multiply(normInv));
   vout.setK(v.getK().multiply(normInv));
   return vout;
 }
Exemplo n.º 6
0
/**
 * Weight units
 *
 * @author Stefan Laubenberger
 * @version 0.1.0, 2013-07-31
 * @since 0.0.1
 */
@XmlRootElement(name = "weight")
public enum Weight implements Unit<Weight> {
  MILLIGRAM(
      Constants.FACTOR_MILLIGRAM_TO_GRAM.multiply(
          Constants.FACTOR_GRAM_TO_KILOGRAM, Constants.DEFAULT_MATHCONTEXT)), // $JUnit$
  GRAM(Constants.FACTOR_GRAM_TO_KILOGRAM), // $JUnit$
  KILOGRAM(BigDecimal.ONE), // $JUnit$
  OUNCE(
      Constants.FACTOR_OUNCE_TO_GRAM.multiply(
          Constants.FACTOR_GRAM_TO_KILOGRAM, Constants.DEFAULT_MATHCONTEXT)), // $JUnit$
  POUND(Constants.FACTOR_POUND_TO_KILOGRAM), // $JUnit$
  TON(
      BigDecimal.ONE.divide(
          Constants.FACTOR_TON_TO_KILOGRAM, Constants.DEFAULT_MATHCONTEXT)); // $JUnit$

  final BigDecimal factor;

  Weight(final BigDecimal factor) {
    this.factor = factor;
  }

  BigDecimal getFactor() {
    return factor;
  }

  /*
   * Implemented methods
   */

  @Override
  public BigDecimal convertTo(final Weight toUnit, final Number value) { // $JUnit$
    if (null == toUnit) {
      throw new RuntimeExceptionIsNull("toUnit"); // $NON-NLS-1$
    }
    if (null == value) {
      throw new RuntimeExceptionIsNull("value"); // $NON-NLS-1$
    }

    final BigDecimal internalValue = new BigDecimal(value.toString());

    return toUnit == this
        ? internalValue
        : internalValue
            .divide(factor, Constants.DEFAULT_MATHCONTEXT)
            .multiply(toUnit.factor, Constants.DEFAULT_MATHCONTEXT);
  }
}
  @AfterViews
  public void afterViews() {
    assetPair = (AssetPair) getArguments().getSerializable(Constants.EXTRA_ASSET_PAIR);
    price = BigDecimal.valueOf(getArguments().getDouble(Constants.EXTRA_RATE_PRICE));

    if (assetPair != null) {
      if (assetPair.getInverted()) {
        accurancy = assetPair.getInvertedAccuracy();
        if (price.compareTo(BigDecimal.ZERO) != 0) {
          price = BigDecimal.ONE.divide(price, accurancy, RoundingMode.HALF_EVEN);
        }
        mainName = assetPair.getQuotingAssetId();
        subName = assetPair.getBaseAssetId();
      } else {
        accurancy = assetPair.getAccuracy();
        mainName = assetPair.getBaseAssetId();
        subName = assetPair.getQuotingAssetId();
      }
    }
    actionBar.setTitle(mainName + "/" + subName);
    if (getArguments().getSerializable(Constants.EXTRA_DESCRIPTION) != null) {
      if (getArguments().getSerializable(Constants.EXTRA_RATE_PRICE) != null) {
        price = (BigDecimal) getArguments().getSerializable(Constants.EXTRA_RATE_PRICE);
        btnBuy.setText(
            String.format(getString(R.string.buy_rate), mainName, subName)
                + " "
                + LykkeUtils.getStriped(accurancy, price));
        btnSell.setText(
            String.format(getString(R.string.sell_at_price), mainName, subName)
                + " "
                + LykkeUtils.getStriped(accurancy, price));
      }
      onSuccess(getArguments().getSerializable(Constants.EXTRA_DESCRIPTION));
    } else {
      setUpVisibility(View.VISIBLE, View.GONE);
      btnBuy.setVisibility(View.GONE);
      btnSell.setVisibility(View.GONE);
      getInfoFromServer();
    }
  }
Exemplo n.º 8
0
  /**
   * Compute the value, in radians, of the arctangent of the inverse of the supplied integer to the
   * specified number of digits after the decimal point. The value is computed using the power
   * series expansion for the arc tangent:
   *
   * <p>arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + (x^9)/9 ...
   */
  public static BigDecimal arctan(int inverseX, int scale) {
    BigDecimal result, numer, term;
    BigDecimal invX = BigDecimal.valueOf(inverseX);
    BigDecimal invX2 = BigDecimal.valueOf(inverseX * inverseX);

    numer = BigDecimal.ONE.divide(invX, scale, roundingMode);

    result = numer;
    int i = 1;
    do {
      numer = numer.divide(invX2, scale, roundingMode);
      int denom = 2 * i + 1;
      term = numer.divide(BigDecimal.valueOf(denom), scale, roundingMode);
      if ((i % 2) != 0) {
        result = result.subtract(term);
      } else {
        result = result.add(term);
      }
      i++;
    } while (term.compareTo(BigDecimal.ZERO) != 0);
    return result;
  }
  private void test(
      final BigDecimal valueToSplit, final int childrenCount, final MathContext mathContext) {
    final String info =
        "ValueToSplit="
            + valueToSplit
            + ", childrenCount="
            + childrenCount
            + ", mathContext="
            + mathContext;
    final int precision = mathContext.getPrecision();

    final BigDecimal splitValueExpected =
        valueToSplit.divide(BigDecimal.valueOf(childrenCount), mathContext);

    // Delta: tolerated difference between calculated split value and actual split value
    // i.e. 1^(-precision) = 1/(1^precision) ... because BigDecimal does not support negative powers
    final BigDecimal splitValueExpectedDelta = BigDecimal.ONE.divide(BigDecimal.ONE.pow(precision));

    // Example: For ValueToSplit=100, childrenCount=33, precision=2
    // splitValueExpected = 0.03
    // splitValueExpectedDelta = 1^(-2) = 0.01

    final MutableAttributeSplitRequest request = createRequest(valueToSplit, childrenCount);

    BigDecimal splitValueSUM = BigDecimal.ZERO;
    for (int index = 0; index < childrenCount; index++) {
      //
      // Update request current index
      request.setAttributeStorageCurrent(request.getAttributeStorages().get(index));
      request.setAttributeStorageCurrentIndex(index);

      //
      // Execute splitting
      final IAttributeSplitResult result = splitter.split(request);

      //
      // Get and check split value
      final BigDecimal splitValue = (BigDecimal) result.getSplitValue();
      assertEquals(
          "Invalid split value on index=" + index + "\n" + info,
          splitValueExpected, // expected
          splitValue, // actual
          splitValueExpectedDelta // delta
          );

      //
      // Update SUM of split values
      splitValueSUM = splitValueSUM.add(splitValue);

      //
      // Update: request's ValueToSplit = last split remaining value
      final BigDecimal remainingValue = (BigDecimal) result.getRemainingValue();
      final BigDecimal remainingValueExpected = valueToSplit.subtract(splitValueSUM);
      assertEquals(
          "Invalid remaining value on index=" + index + "\n" + info,
          remainingValueExpected, // expected
          remainingValue, // actual
          BigDecimal.ZERO // delta=exact
          );
      request.setValueToSplit(remainingValue);
    }

    //
    // Assume: sum of all split values shall be the same as initial value to split
    Assert.assertThat(
        "Invalid splitValues SUM" + "\n" + info,
        splitValueSUM, // actual
        Matchers.comparesEqualTo(valueToSplit) // expected
        );
  }
Exemplo n.º 10
0
  @Override
  public void onSuccess(Object result) {
    try {
      if (getActivity() != null) {
        if (result instanceof DescriptionResult) {
          resultData = (DescriptionResult) result;
          setUpVisibility(View.GONE, View.VISIBLE);
          btnBuy.setVisibility(View.VISIBLE);
          btnSell.setVisibility(View.VISIBLE);
          if (((DescriptionResult) result).getAssetClass() == null) {
            linearAssetName.setVisibility(View.GONE);
            viewAssetClass.setVisibility(View.GONE);
          } else {
            tvAssetClass.setText(((DescriptionResult) result).getAssetClass());
          }
          if (((DescriptionResult) result).getDescription() == null) {
            linearDescription.setVisibility(View.GONE);
            viewDescription.setVisibility(View.GONE);
          } else {
            tvDescription.setText(((DescriptionResult) result).getDescription());
          }

          if (((DescriptionResult) result).getIssuerName() == null) {
            linearIssuerName.setVisibility(View.GONE);
            viewIssuerName.setVisibility(View.GONE);
          } else {
            tvIssuerName.setText(((DescriptionResult) result).getIssuerName());
          }
          if (((DescriptionResult) result).getNumberOfCoins() == null) {
            linearNumberOfCoins.setVisibility(View.GONE);
            viewNumberOfCoins.setVisibility(View.GONE);
          } else {
            tvNumberOfCoins.setText(((DescriptionResult) result).getNumberOfCoins());
          }
          if (((DescriptionResult) result).getMarketCapitalization() == null) {
            linearMarketCapitalization.setVisibility(View.GONE);
            viewMarketCapitalization.setVisibility(View.GONE);
          } else {
            tvMarketCapitalization.setText(((DescriptionResult) result).getMarketCapitalization());
          }
          if (((DescriptionResult) result).getAssetDescriptionUrl() == null) {
            linearDescriptionUrl.setVisibility(View.GONE);
            viewDescriptionUrl.setVisibility(View.GONE);
          } else {

            Spannable s =
                (Spannable) Html.fromHtml(((DescriptionResult) result).getAssetDescriptionUrl());
            for (URLSpan u : s.getSpans(0, s.length(), URLSpan.class)) {
              s.setSpan(
                  new UnderlineSpan() {
                    public void updateDrawState(TextPaint tp) {
                      tp.setUnderlineText(false);
                    }
                  },
                  s.getSpanStart(u),
                  s.getSpanEnd(u),
                  0);
            }

            tvDescriptionUrl.setMovementMethod(LinkMovementMethod.getInstance());
            tvDescriptionUrl.setLinksClickable(true);
            tvDescriptionUrl.setText(s);
          }
          Resources r = getResources();
          float px =
              TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
          float pxMargin =
              TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, r.getDisplayMetrics());
          linearPop.removeAllViews();

          for (int i = 0; i < Integer.parseInt(((DescriptionResult) result).getPopIndex()); i++) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setImageResource(R.drawable.star);
            LinearLayout.LayoutParams lp =
                new LinearLayout.LayoutParams(Math.round(px), Math.round(px));
            lp.setMargins(Math.round(pxMargin), 0, Math.round(pxMargin), 0);
            imageView.setLayoutParams(lp);

            linearPop.addView(imageView);
          }

          if (Integer.parseInt(((DescriptionResult) result).getPopIndex()) == 0) {
            linearPopularity.setVisibility(View.GONE);
          }
          handler.post(run);
        } else if (result instanceof RateResult) {
          if (((RateResult) result).getRate() != null
              && ((RateResult) result).getRate().getAsk() != null
              && getActivity() != null) {
            price = BigDecimal.valueOf(((RateResult) result).getRate().getAsk());
            if (assetPair.getInverted()) {
              price = BigDecimal.ONE.divide(price, accurancy, RoundingMode.HALF_EVEN);
            }
            btnBuy.setText(
                String.format(getString(R.string.buy_rate), mainName, subName)
                    + " "
                    + LykkeUtils.getStriped(accurancy, price));
          }
          if (((RateResult) result).getRate() != null
              && ((RateResult) result).getRate().getBid() != null
              && getActivity() != null) {
            bid = BigDecimal.valueOf(((RateResult) result).getRate().getBid());
            if (assetPair.getInverted()) {
              bid = BigDecimal.ONE.divide(bid, accurancy, RoundingMode.HALF_EVEN);
            }
            btnSell.setText(
                String.format(getString(R.string.sell_at_price), mainName, subName)
                    + " "
                    + LykkeUtils.getStriped(accurancy, bid));
          }
        }
      }
    } catch (NullPointerException ex) {

    }
  }
Exemplo n.º 11
0
 public BigDecimal randHiveBigDecimalInverse(Random r, BigDecimal bigDecimal) {
   if (bigDecimal.signum() == 0) {
     return bigDecimal;
   }
   return BigDecimal.ONE.divide(bigDecimal);
 }
Exemplo n.º 12
0
/** The type Area manager. */
public class AreaManager {

  private static final BigDecimal SQ_MILE_TO_SQ_KM = new BigDecimal(2.589988110336);
  private static final BigDecimal SQ_CM_TO_SQ_INCH = new BigDecimal(0.1550003100006);
  private static final BigDecimal HECTRE_TO_SQ_INCH = new BigDecimal(15500031.00006);
  private static final BigDecimal SQ_KM_TO_SQ_INCH = new BigDecimal(1550003100.006);
  private static final BigDecimal SQ_YARD_TO_SQ_KM =
      BigDecimal.ONE.divide(new BigDecimal(1195990.046301), Constant.MC);
  private static final BigDecimal SQ_FT_TO_SQ_KM =
      BigDecimal.ONE.divide(new BigDecimal(10763910.41671), Constant.MC);
  private static final BigDecimal SQ_INCH_TO_SQ_KM =
      BigDecimal.ONE.divide(SQ_KM_TO_SQ_INCH, Constant.MC);

  private static boolean isCommonRuleApplicable(AreaEnum sourceType, AreaEnum targetType) {
    boolean s =
        (sourceType == AreaEnum.SQ_MILE
            || sourceType == AreaEnum.SQ_YARD
            || sourceType == AreaEnum.SQ_FOOT
            || sourceType == AreaEnum.SQ_INCH);
    boolean t =
        (targetType == AreaEnum.SQ_KM
            || targetType == AreaEnum.HECTARE
            || targetType == AreaEnum.SQ_METER
            || targetType == AreaEnum.SQ_CM);
    if (s && t) {
      return false;
    }
    return true;
  }

  /**
   * Gets common converted amount from high to low.
   *
   * @param sourceType the source type
   * @param targetType the target type
   * @param amount the amount
   * @return common converted amount from high to low
   */
  public static BigDecimal getCommonConvertedAmountFromHighToLow(
      AreaEnum sourceType, AreaEnum targetType, BigDecimal amount) {
    if (sourceType == targetType) {
      return amount;
    }
    BigDecimal result = amount;
    boolean startFlag = false;
    for (AreaEnum t : AreaEnum.values()) {
      if (sourceType == t && startFlag == false) {
        startFlag = true;
        continue;
      }
      if (startFlag) {
        BigDecimal srcAmountVal = t.getUpperToLowerVal();
        result = result.multiply(srcAmountVal);
        if (t == targetType) {
          break;
        }
      }
    }
    return result;
  }

  /**
   * 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);
  }

  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);
  }

  /**
   * Gets converted amount.
   *
   * @param sourceType the source type
   * @param targetType the target type
   * @param amount the amount
   * @return the converted amount
   */
  public static BigDecimal getConvertedAmount(
      AreaEnum sourceType, AreaEnum targetType, BigDecimal amount) {
    if (sourceType == targetType) {
      return amount;
    }
    if (isSourceToTargetOrderDescending(sourceType, targetType, amount)) {
      return getConvertedAmountFromHighToLow(sourceType, targetType, amount);
    }
    return getConvertedAmountFromLowToHigh(sourceType, targetType, amount);
  }

  private static boolean isSourceToTargetOrderDescending(
      AreaEnum sourceType, AreaEnum targetType, BigDecimal amount) {
    boolean flag = false;
    for (AreaEnum t : AreaEnum.values()) {
      if (sourceType == t) {
        flag = true;
        break;
      }
      if (targetType == t) {
        flag = false;
        break;
      }
    }
    return flag;
  }

  private static BigDecimal getConvertedAmountFromLowToHigh(
      AreaEnum sourceType, AreaEnum targetType, BigDecimal amount) {
    BigDecimal updatedAmount = null;
    if (sourceType == targetType) {
      return amount;
    }
    if (isCommonRuleApplicable(targetType, sourceType)) {
      updatedAmount = getCommonConvertedAmountFromLowToHigh(sourceType, targetType, amount, amount);
      return updatedAmount.abs(Constant.MC);
    }
    // First convert everything to inch, the middle point
    if (sourceType == AreaEnum.SQ_CM) {
      updatedAmount = SQ_CM_TO_SQ_INCH;
    } else if (sourceType == AreaEnum.SQ_METER) {
      updatedAmount = Constant.TEN_THOUSAND.multiply(SQ_CM_TO_SQ_INCH);
    } else if (sourceType == AreaEnum.HECTARE) {
      updatedAmount = HECTRE_TO_SQ_INCH;
    } else if (sourceType == AreaEnum.SQ_KM) {
      updatedAmount = SQ_KM_TO_SQ_INCH;
    }

    updatedAmount = updatedAmount.multiply(amount);
    updatedAmount =
        getCommonConvertedAmountFromLowToHigh(AreaEnum.SQ_INCH, targetType, amount, updatedAmount);
    return updatedAmount;
  }
}
Exemplo n.º 13
0
  /**
   * Formats the specified number and returns a string representation.
   *
   * @param item item
   * @param pics pictures
   * @param ii input info
   * @return picture variables
   * @throws QueryException query exception
   */
  private byte[] format(final ANum item, final Picture[] pics, final InputInfo ii)
      throws QueryException {

    // Rule 1: return results for NaN
    final double d = item.dbl(ii);
    if (Double.isNaN(d)) return nan;

    // Rule 2: check if value if negative (smaller than zero or -0)
    final boolean neg = d < 0 || d == 0 && Double.doubleToLongBits(d) == Long.MIN_VALUE;
    final Picture pic = pics[neg && pics.length == 2 ? 1 : 0];
    final IntList res = new IntList(), intgr = new IntList(), fract = new IntList();
    int exp = 0;

    // Rule 3: percent/permille
    ANum num = item;
    if (pic.pc) num = (ANum) Calc.MULT.ev(num, Int.get(100), ii);
    if (pic.pm) num = (ANum) Calc.MULT.ev(num, Int.get(1000), ii);

    if (Double.isInfinite(num.dbl(ii))) {
      // Rule 4: infinity
      intgr.add(new TokenParser(inf).toArray());
    } else {
      // Rule 5: exponent
      if (pic.minExp != 0 && d != 0) {
        BigDecimal dec = num.dec(ii).abs().stripTrailingZeros();
        int scl = 0;
        if (dec.compareTo(BigDecimal.ONE) >= 0) {
          scl = dec.setScale(0, RoundingMode.HALF_DOWN).precision();
        } else {
          while (dec.compareTo(BigDecimal.ONE) < 0) {
            dec = dec.multiply(BigDecimal.TEN);
            scl--;
          }
          scl++;
        }
        exp = scl - pic.min[0];
        if (exp != 0) {
          final BigDecimal n = BigDecimal.TEN.pow(Math.abs(exp));
          num = (ANum) Calc.MULT.ev(num, Dec.get(exp > 0 ? BigDecimal.ONE.divide(n) : n), ii);
        }
      }
      num = num.round(pic.maxFrac, true).abs();

      // convert positive number to string
      final String s =
          (num instanceof Dbl || num instanceof Flt
                  ? Dec.get(BigDecimal.valueOf(num.dbl(ii)))
                  : num)
              .toString();

      // integer/fractional separator
      final int sep = s.indexOf('.');

      // create integer part
      final int sl = s.length();
      final int il = sep == -1 ? sl : sep;
      for (int i = il; i < pic.min[0]; ++i) intgr.add(zero);
      // fractional number: skip leading 0
      if (!s.startsWith("0.") || pic.min[0] > 0) {
        for (int i = 0; i < il; i++) intgr.add(zero + s.charAt(i) - '0');
      }

      // squeeze in grouping separators
      if (pic.group[0].length == 1 && pic.group[0][0] > 0) {
        // regular pattern with repeating separators
        for (int p = intgr.size() - (neg ? 2 : 1); p > 0; --p) {
          if (p % pic.group[0][0] == 0) intgr.insert(intgr.size() - p, grouping);
        }
      } else {
        // irregular pattern, or no separators at all
        final int gl = pic.group[0].length;
        for (int g = 0; g < gl; ++g) {
          final int pos = intgr.size() - pic.group[0][g];
          if (pos > 0) intgr.insert(pos, grouping);
        }
      }

      // create fractional part
      final int fl = sep == -1 ? 0 : sl - il - 1;
      if (fl != 0) for (int i = sep + 1; i < sl; i++) fract.add(zero + s.charAt(i) - '0');
      for (int i = fl; i < pic.min[1]; ++i) fract.add(zero);

      // squeeze in grouping separators in a reverse manner
      final int ul = fract.size();
      for (int p = pic.group[1].length - 1; p >= 0; p--) {
        final int pos = pic.group[1][p];
        if (pos < ul) fract.insert(pos, grouping);
      }
    }

    // add minus sign
    if (neg && pics.length != 2) res.add(minus);
    // add prefix and integer part
    res.add(pic.prefSuf[0].toArray()).add(intgr.finish());
    // add fractional part
    if (!fract.isEmpty()) res.add(decimal).add(fract.finish());
    // add exponent
    if (pic.minExp != 0) {
      res.add(exponent);
      if (exp < 0) res.add(minus);
      final String s = Integer.toString(Math.abs(exp));
      final int sl = s.length();
      for (int i = sl; i < pic.minExp; i++) res.add(zero);
      for (int i = 0; i < sl; i++) res.add(zero + s.charAt(i) - '0');
    }
    // add suffix
    res.add(pic.prefSuf[1].toArray());
    return new TokenBuilder(res.finish()).finish();
  }
Exemplo n.º 14
0
 public static BigDecimal inverse(BigDecimal rate) {
   return BigDecimal.ONE.divide(rate, 10, BigDecimal.ROUND_HALF_DOWN);
 }
Exemplo n.º 15
0
 public ExchangeRate inverse() {
   BigDecimal inverse = BigDecimal.ONE.divide(value, 10, BigDecimal.ROUND_HALF_DOWN);
   return new ExchangeRate(time, inverse);
 }
Exemplo n.º 16
0
  public static BigDecimal sqrt(BigDecimal squarD, int scalar) {
    // Static constants - perhaps initialize in class Vladimir!
    BigDecimal TWO = new BigDecimal(2);
    double SQRT_10 = 3.162277660168379332;
    MathContext rootMC = new MathContext(scalar);

    // General number and precision checking
    int sign = squarD.signum();
    if (sign == -1) throw new ArithmeticException("\nSquare root of a negative number: " + squarD);
    else if (sign == 0) return squarD.round(rootMC);

    int prec = rootMC.getPrecision(); // the requested precision
    if (prec == 0)
      throw new IllegalArgumentException("\nMost roots won't have infinite precision = 0");

    // Initial precision is that of double numbers 2^63/2 ~ 4E18
    int BITS = 62; // 63-1 an even number of number bits
    int nInit = 16; // precision seems 16 to 18 digits
    MathContext nMC = new MathContext(18, RoundingMode.HALF_UP);

    // Iteration variables, for the square root x and the reciprocal v
    BigDecimal x = null, e = null; // initial x: x0 ~ sqrt()
    BigDecimal v = null, g = null; // initial v: v0 = 1/(2*x)

    // Estimate the square root with the foremost 62 bits of squarD
    BigInteger bi = squarD.unscaledValue(); // bi and scale are a tandem
    int biLen = bi.bitLength();
    int shift = Math.max(0, biLen - BITS + (biLen % 2 == 0 ? 0 : 1)); // even
    // shift..
    bi = bi.shiftRight(shift); // ..floors to 62 or 63 bit BigInteger

    double root = Math.sqrt(bi.doubleValue());
    BigDecimal halfBack = new BigDecimal(BigInteger.ONE.shiftLeft(shift / 2));

    int scale = squarD.scale();
    if (scale % 2 == 1) // add half scales of the root to odds..
    root *= SQRT_10; // 5 -> 2, -5 -> -3 need half a scale more..
    scale = (int) Math.floor(scale / 2.); // ..where 100 -> 10 shifts the
    // scale

    // Initial x - use double root - multiply by halfBack to unshift - set
    // new scale
    x = new BigDecimal(root, nMC);
    x = x.multiply(halfBack, nMC); // x0 ~ sqrt()
    if (scale != 0) x = x.movePointLeft(scale);

    if (prec < nInit) // for prec 15 root x0 must surely be OK
    return x.round(rootMC); // return small prec roots without
    // iterations

    // Initial v - the reciprocal
    v = BigDecimal.ONE.divide(TWO.multiply(x), nMC); // v0 = 1/(2*x)

    // Collect iteration precisions beforehand
    ArrayList<Integer> nPrecs = new ArrayList<Integer>();

    assert nInit > 3 : "Never ending loop!"; // assume nInit = 16 <= prec

    // Let m be the exact digits precision in an earlier! loop
    for (int m = prec + 1; m > nInit; m = m / 2 + (m > 100 ? 1 : 2)) nPrecs.add(m);

    // The loop of "Square Root by Coupled Newton Iteration" for simpletons
    for (int i = nPrecs.size() - 1; i > -1; i--) {
      // Increase precision - next iteration supplies n exact digits
      nMC =
          new MathContext(
              nPrecs.get(i), (i % 2 == 1) ? RoundingMode.HALF_UP : RoundingMode.HALF_DOWN);

      // Next x // e = d - x^2
      e = squarD.subtract(x.multiply(x, nMC), nMC);
      if (i != 0) x = x.add(e.multiply(v, nMC)); // x += e*v ~ sqrt()
      else {
        x = x.add(e.multiply(v, rootMC), rootMC); // root x is ready!
        break;
      }

      // Next v // g = 1 - 2*x*v
      g = BigDecimal.ONE.subtract(TWO.multiply(x).multiply(v, nMC));

      v = v.add(g.multiply(v, nMC)); // v += g*v ~ 1/2/sqrt()
    }

    return x; // return sqrt(squarD) with precision of rootMC
  }