public UserKDRRecordStats(long recordCount, long kills, long deaths, long suicides, User favoriteTarget) { super(recordCount, deaths, kills); this.suicides = suicides; this.favoriteTarget = favoriteTarget; // The KDR ratio as KILLS/DEATHS/SUICIDES String suicideRatio; if (suicides > 0) { suicideRatio = new BigDecimal((double) losses / (double) suicides) .setScale(1, RoundingMode.HALF_UP) .toString(); } else { suicideRatio = "0"; } this.kdr = MathUtils.asFraction(wins, losses) + '/' + suicideRatio; }
@Test // tested: All public void testGlobal() { Map<String, AddOnNotionalFactor> factors = new HashMap<>(); factors.put(AN1.getProduct(), AN1); factors.put(AN2.getProduct(), AN2); Map<String, List<AddOnNotional>> notional = new HashMap<>(); notional.put(AN3.getProduct(), Arrays.asList(AN3, AN4, AN5)); notional.put(AN6.getProduct(), Arrays.asList(AN6, AN7)); notional.put(AN8.getProduct(), Arrays.asList(AN8)); notional.put(AN9.getProduct(), Arrays.asList(AN9)); Map<ProductClass, ProductMultiplier> multipliers = new HashMap<>(); multipliers.put(CM12.getProductClass(), CM12); multipliers.put(IR10.getProductClass(), IR10); multipliers.put(EQ12.getProductClass(), EQ12); multipliers.put(CQ16.getProductClass(), CQ16); List<Sensitivity> s = Arrays.asList(CM1, CM2, CM3, CM4, CM5, CM6, CM7, CM8, CM9, CM10, CM11, CQ1, CQ2, CQ3, CQ4, CQ5, CQ6, CQ7, CQ8, CQ9, CQ10, CQ11, CQ12, CQ13, CQ14, CQ15, BC1, BC2, BC3, BC4, CNQ1, CNQ2, CNQ3, CNQ4, CNQ5, CNQ6, CNQ7, CNQ8, EQ1, EQ2, EQ3, EQ4, EQ5, EQ6, EQ7, EQ8, EQ9, EQ10, EQ11, IR1, IR2, IR3, IR4, IR5, IR6, IR7, IR8, IR9, FX1, FX2, FX3, FX4, CMV1, CMV2, CMV3, CMV4, CMV5, CMV6, CQV1, CQV2, CQV3, CQV4, CQV5, CNQV1, CNQV2, CNQV3, CNQV4, CNQV5, EQV1, EQV2, EQV3, EQV4, EQV5, EQV6, EQV7, EQV8, EQV9, EQV10, FXV1, FXV2, FXV3, FXV4, FXV5, IRV1, IRV2, IRV3, IRV4, IRV5, IRV6, IRV7); Assert.assertEquals(new BigDecimal("20991954959"), simm.calculateAdditional(s, multipliers, factors, notional, AN10).setScale(0, RoundingMode.HALF_UP)); }
public void testWorstCase() { int n = 2000000; int k = 200000; final long[] compareCalls = {0}; Comparator<Integer> cmp = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { compareCalls[0]++; return o1.compareTo(o2); } }; TopKSelector<Integer> top = TopKSelector.least(k, cmp); top.offer(1); for (int i = 1; i < n; i++) { top.offer(0); } assertThat(top.topK()).containsExactlyElementsIn(Collections.nCopies(k, 0)); assertThat(compareCalls[0]).isAtMost(10L * n * IntMath.log2(k, RoundingMode.CEILING)); }
@GwtIncompatible // TODO @AndroidIncompatible // TODO(cpovirk): File BigDecimal.divide() rounding bug. public void testDivNonZero() { for (long p : NONZERO_LONG_CANDIDATES) { for (long q : NONZERO_LONG_CANDIDATES) { for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) { long expected = new BigDecimal(valueOf(p)).divide(new BigDecimal(valueOf(q)), 0, mode).longValue(); long actual = LongMath.divide(p, q, mode); if (expected != actual) { failFormat("expected divide(%s, %s, %s) = %s; got %s", p, q, mode, expected, actual); } } } } }
private static double calculate(String data) { int[] counts = new int[26]; Arrays.fill(counts, 0); int index, totalChars = 0; double numer = 0.0, denom; data = data.toLowerCase(); for (Character c : data.toLowerCase().toCharArray()) { if (Character.isAlphabetic(c)) { index = c - 'a'; ++counts[index]; ++totalChars; } } for (Integer n : counts) { numer += (n * (n - 1)); } denom = totalChars * (totalChars - 1); return BigDecimal.valueOf((numer / denom)).setScale(15, RoundingMode.HALF_UP).doubleValue(); }
public void listRewards(Player player, VirtualCrate vc){ if(!vc.showRewardsOnLeft) return; /* Home */ StateContainer test = new StateContainer(); Page.PageBuilder rewards = Page.builder(); rewards.setAutoPaging(true); rewards.setTitle(TextSerializers.FORMATTING_CODE.deserialize(vc.displayName + " Rewards")); rewards.setEmptyStack(ItemStack.builder() .itemType(ItemTypes.STAINED_GLASS_PANE) .add(Keys.DYE_COLOR, DyeColors.BLACK) .add(Keys.DISPLAY_NAME, Text.of(TextColors.DARK_GRAY, "HuskyCrates")).build()); for(Object[] e : vc.getItemSet()){ CrateReward rew = (CrateReward)e[1]; ItemStack item = rew.getDisplayItem().copy(); if(vc.showProbability) { ArrayList<Text> lore = (ArrayList<Text>) item.getOrElse(Keys.ITEM_LORE, new ArrayList<>()); lore.add(Text.of()); lore.add(Text.of(TextColors.GRAY, TextStyles.ITALIC, "Win Probability: " + BigDecimal.valueOf((rew.getChance() / vc.getMaxProb()) * 100d).setScale(1, RoundingMode.HALF_UP).toString() + "%")); item.offer(Keys.ITEM_LORE, lore); } rewards.addElement(new Element(item)); } test.setInitialState(rewards.build("rewards")); test.launchFor(player); }
/** * Given an ILP payment package final destination amount, reduce the value by a configured amount of allowable * slippage. * * Slippage occurs when the actual FX-rates between a quoted amount and an actual amount diverge due to various * factors outside of the control of the FX engine. For example, during quoting, the FX-rate may be 2:1, meaning 2 * units of a source currency can be exchanged for 1 unit of a terminating currency. Thus, a sender sending 2 units * should expect 1 unit to arrive at the final destination. However, if by the time the payment is actually made, the * rates have "slipped" to 3:1, it is now more expensive for the sender to get 1 unit to the receiver. Thus, sending 2 * units would only allow 2/3 of the terminating unit to arrive at the reciever, which means the amount of money the * receiver would receive has also "slipped." Because certain ledgers cannot guarantee quoted pricing, this connector * tolerates a certain amount of slippage as configured in {@link ConnectorConfig#getDefaultSlippagePercent()}. * * @param ilpPaymentDestinationAmount A {@link BigInteger} representing the amount, in units of the final-destination * ledger, of the ILP payment. */ @VisibleForTesting protected BigInteger calculateIlpPacketDestinationAmountWithSlippage( final BigInteger ilpPaymentDestinationAmount, final InterledgerAddress destinationLedgerPrefix ) { Objects.requireNonNull(ilpPaymentDestinationAmount); InterledgerAddress.requireAddressPrefix(destinationLedgerPrefix); // The amount can "slip" down by up-to {slippagePercent} final BigDecimal slippagePercent = this.connectorConfigurationService.getConnectorConfig() .getDefaultSlippagePercent(); // Formula: amount * (1 - slippagePercent) => 500 * (1 - 1%) => 500 * (0.99) => 495 final BigDecimal percentageInDecimal = BigDecimal.ONE.subtract(slippagePercent); return new BigDecimal(ilpPaymentDestinationAmount) // Uses infinite precision, which is simply signficant digits (not scale nor total number of digits). .multiply(percentageInDecimal).setScale(0, RoundingMode.HALF_UP) // Should never throw an exception because scale was set to 0 above. .toBigIntegerExact(); }
public MonetaryFormat() { // defaults this.negativeSign = '-'; this.positiveSign = 0; // none this.zeroDigit = '0'; this.decimalMark = '.'; this.minDecimals = 2; this.decimalGroups = null; this.shift = 0; this.roundingMode = RoundingMode.HALF_UP; this.codes = new String[MAX_DECIMALS]; this.codes[0] = CODE_BTC; this.codes[3] = CODE_MBTC; this.codes[6] = CODE_UBTC; this.codeSeparator = ' '; this.codePrefixed = true; }
/** * Rounds values by using a scale of 2 and rounding mode half up. If a non * rounded value equals zero (i.e. one of the factors is zero) convert it to * an empty string. * * @param formatter * @param value * @param factors * used in the price calculation * @return */ public static String roundValue(PriceConverter formatter, BigDecimal value, BigDecimal... factors) { if (BigDecimal.ZERO.compareTo(value) == 0) { if (factors.length == 0) { return EMPTY_STRING; } else if (containsZeroFactor(factors)) { return EMPTY_STRING; } } return formatter.getValueToDisplay(value.setScale( PriceConverter.NORMALIZED_PRICE_SCALING, RoundingMode.HALF_UP), true); }
protected Optional<ITransaction> getTransaction(IInvntry invntry) { BigDecimal roq = orderManagementService.computeRecommendedOrderQuantity(invntry); if(BigUtil.greaterThanZero(roq)) { try { ITransaction t = JDOUtils.createInstance(ITransaction.class); t.setKioskId(invntry.getKioskId()); t.setMaterialId(invntry.getMaterialId()); t.setQuantity(roq.setScale(0, RoundingMode.CEILING)); t.setType(ITransaction.TYPE_ORDER); t.setDomainId(invntry.getDomainId()); t.setSourceUserId(Constants.SYSTEM_USER_ID); t.setTimestamp(new Date()); t.setBatchId(null); t.setBatchExpiry(null); t.setReason("AUTOMATED"); Optional<IKioskLink> vendor = chooseVendor(invntry.getKioskId(), invntry.getMaterialId()); t.setLinkedKioskId(vendor.isPresent() ? vendor.get().getLinkedKioskId() : null); return Optional.of(t); } catch (ServiceException e) { LOGGER.warn("Error choosing vendor for inventory {0}:{1}", invntry.getKioskId(), invntry.getMaterialId(), e); } } return Optional.empty(); }
public void initialize() { // 0-4 rounds down, 5-9 rounds up currency.setRoundingMode(RoundingMode.HALF_UP); // listener for changes to tipPercentageSlider's value tipPercentageSlider.valueProperty().addListener( new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> ov, Number oldValue, Number newValue) { tipPercentage = BigDecimal.valueOf(newValue.intValue() / 100.0); tipPercentageLabel.setText(percent.format(tipPercentage)); } } ); }
/** * Calculates the VAT details for the given VAT and cost data. * * @param vatForCustomer * The VAT details to be considered. * @return The VAT details containing the VAT amount and the total amount. */ public static VatRateDetails calculateVATCosts(VatRateDetails vatForCustomer) { BigDecimal totalCosts = vatForCustomer.getNetCosts(); BigDecimal vatRate = vatForCustomer.getEffectiveVatRateForCustomer(); if (vatRate != null) { BigDecimal fixSum = BigDecimal.ONE; BigDecimal percentBaseFactor = new BigDecimal(100); BigDecimal factor = fixSum.add(vatRate.divide(percentBaseFactor)); BigDecimal total = totalCosts.multiply(factor).setScale( PriceConverter.NORMALIZED_PRICE_SCALING, RoundingMode.HALF_UP); totalCosts = total; } vatForCustomer.setTotalCosts(totalCosts); return vatForCustomer; }
@Test // tested: notional (netting with negative (absolute sum)) public void testAN3() { Map<String, AddOnNotionalFactor> factors = new HashMap<>(); factors.put(AN1.getProduct(), AN1); Map<String, List<AddOnNotional>> notional = new HashMap<>(); notional.put(AN3.getProduct(), Arrays.asList(AN3, AN4, AN5)); Assert.assertEquals(new BigDecimal("2747250"), simm.calculateAdditional(EMPTY_LIST, EMPTY_MULT, factors, notional, ZERO_FIXED).setScale(0, RoundingMode.HALF_UP)); }
public void testLog2NegativeAlwaysThrows() { for (int x : NEGATIVE_INTEGER_CANDIDATES) { for (RoundingMode mode : ALL_ROUNDING_MODES) { try { IntMath.log2(x, mode); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } }
/** * 判断data的类型,尝试解析成日期类型(返回{@link Date}),其次布尔类型(返回{@link Boolean}), * 然后数字类型(转变成字符串输出), * 前三种均解析失败则直接返回字符串data * * @param data * @return 解析后的值 */ private Object getValue(String data) { Object value = null; try { //判断是否是日期类型 Date date = DateUtils.parseDate(data, DATE_PATTERN); value = date; } catch (ParseException e) { //抛异常证明非日期类型 if ("true".equalsIgnoreCase(data)) { value = Boolean.TRUE; } else if ("false".equalsIgnoreCase(data)) { value = Boolean.FALSE; } else { //判断是否数字 try { double dbl = Double.parseDouble(data); if (this.scale == null || this.scale <= 0) { //不四舍五入,直接输出 value = data; } else { BigDecimal bd = new BigDecimal(dbl); value = bd.toString().contains(".") ? bd.setScale(this.scale, RoundingMode.HALF_UP).toString() : bd.toString(); } } catch (NumberFormatException e1) { //证明不是数字,直接输出 value = data; } } } return value; }
@Override protected Position handlePosition(Position position) { double distance = 0.0; if (position.getAttributes().containsKey(Position.KEY_DISTANCE)) { distance = position.getDouble(Position.KEY_DISTANCE); } double totalDistance = 0.0; Position last = getLastPosition(position.getDeviceId()); if (last != null) { totalDistance = last.getDouble(Position.KEY_TOTAL_DISTANCE); if (!position.getAttributes().containsKey(Position.KEY_DISTANCE)) { distance = DistanceCalculator.distance( position.getLatitude(), position.getLongitude(), last.getLatitude(), last.getLongitude()); distance = BigDecimal.valueOf(distance).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); } if (filter && last.getValid() && last.getLatitude() != 0 && last.getLongitude() != 0) { boolean satisfiesMin = coordinatesMinError == 0 || distance > coordinatesMinError; boolean satisfiesMax = coordinatesMaxError == 0 || distance < coordinatesMaxError || position.getValid(); if (!satisfiesMin || !satisfiesMax) { position.setLatitude(last.getLatitude()); position.setLongitude(last.getLongitude()); distance = 0; } } } position.set(Position.KEY_DISTANCE, distance); totalDistance = BigDecimal.valueOf(totalDistance + distance).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); position.set(Position.KEY_TOTAL_DISTANCE, totalDistance); return position; }
@Override public BigDecimal scaleTo(BigDecimal value, Units<Q> units) { if (units == this) { return value; } ScaledUnits<Q> scaledUnits = (ScaledUnits<Q>) units; return value.divide(scaledUnits.factor, 6, RoundingMode.HALF_UP).stripTrailingZeros(); }
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath public void testLog10MatchesBigInteger() { for (int x : POSITIVE_INTEGER_CANDIDATES) { for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) { // The BigInteger implementation is tested separately, use it as the reference. assertEquals(BigIntegerMath.log10(valueOf(x), mode), IntMath.log10(x, mode)); } } }
/** * * @param file - файл * @return - размер файла в мегабайтах с окреглением вверх до 2 знаков после запятой */ public Double getLogSizeDouble(String file){ double mb = (double)new File(file).length()/1024/1024; Double truncatedDouble = BigDecimal.valueOf(mb) .setScale(2, RoundingMode.HALF_UP) .doubleValue(); return truncatedDouble; }
private static void checkEqualsWithGivenScale(String message, BigDecimal expected, BigDecimal actual, int scale) { BigDecimal adjustedValue = actual; if (actual != null) { adjustedValue = actual.setScale(scale, RoundingMode.HALF_UP); } assertEquals(message, expected.setScale(scale, RoundingMode.HALF_UP), adjustedValue); }
private void increment() { final TransferProgress progress = meter.getStatus(); if(System.currentTimeMillis() - timestamp.get() < 100L) { if(!progress.isComplete()) { return; } } try { lock.acquire(); final BigDecimal fraction; if(progress.getTransferred() == 0L) { fraction = BigDecimal.ZERO; } else { fraction = new BigDecimal(progress.getTransferred()) .divide(new BigDecimal(progress.getSize()), 1, RoundingMode.DOWN); } console.printf("\r%s[", Ansi.ansi() .saveCursorPosition() .eraseLine(Ansi.Erase.ALL) .restoreCursorPosition()); int i = 0; for(; i <= (int) (fraction.doubleValue() * width); i++) { console.printf("\u25AE"); } for(; i < width; i++) { console.printf(StringUtils.SPACE); } console.printf("] %s%s", progress.getProgress(), Ansi.ansi().reset()); timestamp.set(System.currentTimeMillis()); } catch(InterruptedException e) { // } finally { lock.release(); } }
@GwtIncompatible // TODO @AndroidIncompatible // slow public void testDivNonZero() { for (BigInteger p : NONZERO_BIGINTEGER_CANDIDATES) { for (BigInteger q : NONZERO_BIGINTEGER_CANDIDATES) { for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) { BigInteger expected = new BigDecimal(p).divide(new BigDecimal(q), 0, mode).toBigIntegerExact(); assertEquals(expected, BigIntegerMath.divide(p, q, mode)); } } } }
/** * Rounds a number to a specific place * * @param value Value being rounded * @param places Places being rounded * @return Rounded value */ public static double roundToPlace(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); }
public void execute(Tuple input, BasicOutputCollector collector) { // Get alert event from checkDistanceAndAlert bolt. AlertEvent alertEvent = (AlertEvent) input.getValueByField("alertInfo"); // Reading map containing alerts from Hazelcast AlertEvent previousAlertEvent = vehicleAlertMap.get(alertEvent.getVehicleId()); // Check whether alert is already generated for this vehicle or not. if (previousAlertEvent == null) { // Add entry in Hazelcast Map vehicleAlertMap.put(alertEvent.getVehicleId(), alertEvent); System.out.println(alertEvent.toString()); String message = "ALERT!! Hi, your vehicle id " + alertEvent.getVehicleId() + " is moving out of start location i.e. (" + BigDecimal.valueOf(alertEvent.getActualLatitude()).setScale(2, RoundingMode.HALF_DOWN) .doubleValue() + "," + BigDecimal.valueOf(alertEvent.getActualLongitude()).setScale(2, RoundingMode.HALF_DOWN) .doubleValue() + ") with distance " + BigDecimal.valueOf(alertEvent.getActualDistance()) .setScale(2, RoundingMode.HALF_DOWN).doubleValue(); System.out.println(" GenerateAlertBOLT: >>>>> " + message); // Generate SMS. sendMessage(alertEvent.getPhoneNumber(), message); // Emit tuple for next bolt. collector.emit("generatedAlertInfo", new Values(alertEvent)); } else { System.out.println(" GenerateAlertBOLT: >>>>> Alert is already generated for " + alertEvent.getVehicleId()); } }
public static String formatSignificant(double value, int significant) { MathContext mathContext = new MathContext(significant, RoundingMode.DOWN); BigDecimal bigDecimal = new BigDecimal(value, mathContext); return bigDecimal.toPlainString(); }
public BigDecimal calculateDailyAmountFor(BigDecimal claimAmount, BigDecimal interestRate) { requireNonNull(claimAmount); requireNonNull(interestRate); return claimAmount .multiply(asFraction(interestRate)) .divide(NUMBER_OF_DAYS_IN_YEAR, DIVISION_DECIMAL_SCALE, RoundingMode.HALF_UP) .setScale(TO_FULL_PENNIES, RoundingMode.HALF_UP); }
/** * Normalizes given item amount to {@link Currency#getBase()} currency with * {@link TimePeriod#getBase()} time period */ private ItemMetric createItemMetric(Item item) { BigDecimal amount = ratesService .convert(item.getCurrency(), Currency.getBase(), item.getAmount()) .divide(item.getPeriod().getBaseRatio(), 4, RoundingMode.HALF_UP); return new ItemMetric(item.getTitle(), amount); }
/** * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of ten */ @GwtIncompatible("TODO") @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log10(long x, RoundingMode mode) { checkPositive("x", x); int logFloor = log10Floor(x); long floorPow = powersOf10[logFloor]; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(x == floorPow); // fall through case FLOOR: case DOWN: return logFloor; case CEILING: case UP: return logFloor + lessThanBranchFree(floorPow, x); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5 return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x); default: throw new AssertionError(); } }
@GwtIncompatible // TODO public void testLog10NegativeAlwaysThrows() { for (RoundingMode mode : ALL_ROUNDING_MODES) { try { BigIntegerMath.log10(BigInteger.valueOf(-1), mode); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } }
/** * Calcul grâce au développement limité d'Euler * Génère le point de la clothoïde unitaire de courbure = s * * @param s */ private void calculeXY(BigDecimal sparam, PosBigDecimal out) { BigDecimal s = sparam; out.x = s; BigDecimal factorielle = new BigDecimal(1).setScale(15, RoundingMode.HALF_EVEN); BigDecimal b2 = new BigDecimal(1).setScale(15, RoundingMode.HALF_EVEN); BigDecimal s2 = s.multiply(s); BigDecimal b = b2; s = s.multiply(s2); out.y = s.divide(b.multiply(new BigDecimal(3).setScale(15, RoundingMode.HALF_EVEN)), RoundingMode.HALF_EVEN); BigDecimal seuil = new BigDecimal(0.000000000001).setScale(15, RoundingMode.HALF_EVEN); BigDecimal tmp; long i = 1; do { factorielle = factorielle.multiply(new BigDecimal(2 * i).setScale(15, RoundingMode.HALF_EVEN)); b = b.multiply(b2); s = s.multiply(s2); tmp = s.divide(factorielle.multiply(b).multiply(new BigDecimal(4 * i + 1).setScale(15, RoundingMode.HALF_EVEN)), RoundingMode.HALF_EVEN); if((i & 1) == 0) out.x = out.x.add(tmp); else out.x = out.x.subtract(tmp); factorielle = factorielle.multiply(new BigDecimal(2 * i + 1).setScale(15, RoundingMode.HALF_EVEN)); b = b.multiply(b2); s = s.multiply(s2); tmp = s.divide(factorielle.multiply(b).multiply(new BigDecimal(4 * i + 3).setScale(15, RoundingMode.HALF_EVEN)), RoundingMode.HALF_EVEN); if((i & 1) == 0) out.y = out.y.add(tmp); else out.y = out.y.subtract(tmp); i++; } while(tmp.abs().compareTo(seuil) > 0); // On fait en sorte que tourner à gauche ait une courbure positive out.y = out.y.multiply(new BigDecimal(1000)); // On considère que x et y sont en // millimètre et que la courbure // est en mètre^-1 out.x = out.x.multiply(new BigDecimal(1000)); }
/** * {@inheritDoc} */ @Override public BigDecimal convert(Currency from, Currency to, BigDecimal amount) { Assert.notNull(amount); Map<Currency, BigDecimal> rates = getCurrentRates(); BigDecimal ratio = rates.get(to).divide(rates.get(from), 4, RoundingMode.HALF_UP); return amount.multiply(ratio); }
/** * set sensor value * @param index value index * @param value value */ public void setValue(int index, float value) { if (type.getValueType() != SensorType.ValueType.NUMBER) { return; } try { BigDecimal bd = BigDecimal.valueOf(value); this.values[index] = bd.setScale(type.getValueDecimalPlaces()[index], RoundingMode.HALF_UP).floatValue(); } catch (Exception e) { e.printStackTrace(); } }
/** * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of two */ @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log2(int x, RoundingMode mode) { checkPositive("x", x); switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through case DOWN: case FLOOR: return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x); case UP: case CEILING: return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 int leadingZeros = Integer.numberOfLeadingZeros(x); int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros; // floor(2^(logFloor + 0.5)) int logFloor = (Integer.SIZE - 1) - leadingZeros; return logFloor + lessThanBranchFree(cmp, x); default: throw new AssertionError(); } }
public void startPump() throws Exception { String msg; logger.info("Passed Parameters [{}]", Arrays.toString(args)); validateAndParseArgs(); logger.info("Waiting for Coin Name [example : eth]"); Scanner sc = new Scanner(System.in); coinName = sc.next(); sc.close(); msg = String.format("Coin Name : BTC-%s, BTC Amount %.8f, Profit Percentage %f", coinName.toUpperCase(), btcValue, profitPercentage); logger.info(msg); logger.info("################################### Start Pump Engine ###################################"); BigDecimal currentBid = bittrexApi.getCoinLimit(coinName); BigDecimal proposedBid = currentBid.multiply(buyFacotr); BigDecimal quantity = btcValue.divide(proposedBid.multiply(safeFactor), RoundingMode.DOWN); BigDecimal proposedAsk = currentBid .multiply(profitPercentage.add(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(100))); msg = String.format("Current Bid %.8f, Proposed Quantity %.8f, Proposed Ask %.8f", proposedBid, quantity, proposedAsk); logger.info(msg); String buyOrderId = bittrexApi.placeBuyOrder(apiKey, apiSecret, coinName, quantity, proposedBid); logger.info("Buy Order UUID {}", buyOrderId); bittrexApi.waitOpenOrderToClose(apiKey, apiSecret, buyOrderId); logger.info("Buy Order UUID {} closed, Engine will place sell order id", buyOrderId); String sellOrderId = bittrexApi.placeSellOrder(apiKey, apiSecret, coinName, quantity, proposedAsk); logger.info("Sell Order UUID {}", sellOrderId); logger.info("################################### Sell Order Placed ###################################"); }
public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); }
private BigDecimal getDurationParamCosts(long price, long value, BigDecimal periodFactor) { // add duration param costs BigDecimal paramPrice = BigDecimal.valueOf(price); BigDecimal durationParamCosts = BigDecimal.valueOf(value) .divide(BigDecimal.valueOf(86400000L), BIGDECIMAL_SCALE, RoundingMode.HALF_UP) .multiply(paramPrice).multiply(periodFactor); return durationParamCosts; }
static void formatOutputTestLong(NumberFormat nf, long longToTest, String tiePosition, String inputDigits, String expectedOutput) { int mfd = nf.getMaximumFractionDigits(); RoundingMode rm = nf.getRoundingMode(); String result = nf.format(longToTest); if (!result.equals(expectedOutput)) { System.out.println(); System.out.println("========================================"); System.out.println("***Failure : error formatting value from string : " + inputDigits); System.out.println("NumberFormat pattern is : " + ((DecimalFormat ) nf).toPattern()); System.out.println("Maximum number of fractional digits : " + mfd); System.out.println("Fractional rounding digit : " + (mfd + 1)); System.out.println("Position of value relative to tie : " + tiePosition); System.out.println("Rounding Mode : " + rm); System.out.println( "Error. Formatted result different from expected." + "\nExpected output is : \"" + expectedOutput + "\"" + "\nFormated output is : \"" + result + "\""); System.out.println("========================================"); System.out.println(); errorCounter++; allPassed = false; } else { testCounter++; System.out.print("Success. Long input :" + inputDigits); System.out.print(", rounding : " + rm); System.out.print(", fract digits : " + mfd); System.out.print(", tie position : " + tiePosition); System.out.println(", expected : " + expectedOutput); } }
/** * Realiza o calculo proporcional do último salário que o funcionário irá * receber, levando em conta o total de dias trabalhados no mês e o salário * base do mesmo. * * @param qtdDias Referente ao total de dias trabalhados no último mês. * @param salario Referente ao salário base do funcionário. * */ public BigDecimal calcUltSal(int qtdDias, BigDecimal salario) { BigDecimal salarioFinal = new BigDecimal("0"); if (qtdDias >= 30) { salarioFinal = salario; } else { salarioFinal = new BigDecimal(qtdDias).multiply ((salario.divide(new BigDecimal("30"), 2, RoundingMode.HALF_UP))); } return salarioFinal; }