List of usage examples for java.math MathContext DECIMAL32
MathContext DECIMAL32
To view the source code for java.math MathContext DECIMAL32.
Click Source Link
From source file:roboguice.calculator.activity.CalculatorActivity.java
public void onOperationClicked(View operation) { // Any operation will automatically push the current digits onto the stack as if the user hit 'enter' stack.pushDigitAccumulatorOnStack(); BigDecimal tmp;/*from w ww . j ava 2s . co m*/ switch (operation.getId()) { case R.id.plus: if (stack.size() < 2) break; stack.push(stack.pop().add(stack.pop())); break; case R.id.minus: if (stack.size() < 2) break; tmp = stack.pop(); stack.push(stack.pop().subtract(tmp)); break; case R.id.multiply: if (stack.size() < 2) break; stack.push(stack.pop().multiply(stack.pop())); break; case R.id.divide: if (stack.size() < 2) break; tmp = stack.pop(); stack.push(stack.pop().divide(tmp, MathContext.DECIMAL32)); break; case R.id.delete: if (stack.size() >= 1) stack.pop(); break; } refreshDisplay(); }
From source file:org.fede.util.Util.java
private static BigDecimal avg(List<BigDecimal> list) { if (list.isEmpty()) { return BigDecimal.ZERO; }//from ww w .j av a 2 s . com return list.stream().reduce(BigDecimal.ZERO, (left, right) -> left.add(right)) .setScale(7, RoundingMode.HALF_UP).divide(new BigDecimal(list.size()), MathContext.DECIMAL32); }
From source file:burstcoin.jminer.JMinerCommandLine.java
private void initApplicationListeners() { context.addApplicationListener(new ApplicationListener<RoundFinishedEvent>() { @Override//from w w w .j a va 2 s . co m public void onApplicationEvent(RoundFinishedEvent event) { previousRemainingCapacity = 0; previousElapsedTime = 0; long s = event.getRoundTime() / 1000; long ms = event.getRoundTime() % 1000; String bestDeadline = Long.MAX_VALUE == event.getBestCommittedDeadline() ? "N/A" : String.valueOf(event.getBestCommittedDeadline()); LOG.info("FINISH block '" + event.getBlockNumber() + "', " + "best deadline '" + bestDeadline + "', " + "round time '" + s + "s " + ms + "ms'"); } }); context.addApplicationListener(new ApplicationListener<RoundStoppedEvent>() { @Override public void onApplicationEvent(RoundStoppedEvent event) { previousRemainingCapacity = 0; previousElapsedTime = 0; long s = event.getElapsedTime() / 1000; long ms = event.getElapsedTime() % 1000; BigDecimal totalCapacity = new BigDecimal(event.getCapacity()); BigDecimal factor = BigDecimal.ONE.divide(totalCapacity, MathContext.DECIMAL32); BigDecimal progress = factor .multiply(new BigDecimal(event.getCapacity() - event.getRemainingCapacity())); int percentage = (int) Math.ceil(progress.doubleValue() * 100); percentage = percentage > 100 ? 100 : percentage; String bestDeadline = Long.MAX_VALUE == event.getBestCommittedDeadline() ? "N/A" : String.valueOf(event.getBestCommittedDeadline()); LOG.info("STOP block '" + event.getBlockNumber() + "', " + String.valueOf(percentage) + "% done, " + "best deadline '" + bestDeadline + "', " + "elapsed time '" + s + "s " + ms + "ms'"); } }); context.addApplicationListener(new ApplicationListener<NetworkLastWinnerEvent>() { @Override public void onApplicationEvent(NetworkLastWinnerEvent event) { if (blockNumber - 1 == event.getLastBlockNumber()) { LOG.info( " winner block '" + event.getLastBlockNumber() + "', '" + event.getWinner() + "'"); } else { LOG.error("Error: NetworkLastWinnerEvent for block: " + event.getLastBlockNumber() + " is outdated!"); } } }); context.addApplicationListener(new ApplicationListener<NetworkStateChangeEvent>() { @Override public void onApplicationEvent(NetworkStateChangeEvent event) { blockNumber = event.getBlockNumber(); } }); context.addApplicationListener(new ApplicationListener<RoundStartedEvent>() { @Override public void onApplicationEvent(RoundStartedEvent event) { progressLogStep = NUMBER_OF_PROGRESS_LOGS_PER_ROUND; LOG.info("-------------------------------------------------------"); LOG.info("START block '" + event.getBlockNumber() + "', " + "scoopNumber '" + event.getScoopNumber() + "', " + "capacity '" + event.getCapacity() / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR + " " + G_UNIT + "'"); String target = event.getTargetDeadline() == Long.MAX_VALUE ? "N/A" : String.valueOf(event.getTargetDeadline()); LOG.info(" targetDeadline '" + target + "', " + "baseTarget '" + String.valueOf(event.getBaseTarget()) + "'"); } }); context.addApplicationListener(new ApplicationListener<ReaderProgressChangedEvent>() { @Override public void onApplicationEvent(ReaderProgressChangedEvent event) { long logStepCapacity = event.getCapacity() / NUMBER_OF_PROGRESS_LOGS_PER_ROUND; if (event.getRemainingCapacity() < logStepCapacity * progressLogStep || event.getRemainingCapacity() == 0) { progressLogStep--; // trigger garbage collection on every progress step System.gc(); BigDecimal totalCapacity = new BigDecimal(event.getCapacity()); BigDecimal factor = BigDecimal.ONE.divide(totalCapacity, MathContext.DECIMAL32); BigDecimal progress = factor .multiply(new BigDecimal(event.getCapacity() - event.getRemainingCapacity())); int percentage = (int) Math.ceil(progress.doubleValue() * 100); percentage = percentage > 100 ? 100 : percentage; // calculate capacity long effMBPerSec = 0; if (previousRemainingCapacity > 0) { long effDoneBytes = previousRemainingCapacity - event.getRemainingCapacity(); // calculate current reading speed (since last info) long effBytesPerMs = (effDoneBytes / 4096) / (event.getElapsedTime() - previousElapsedTime); effMBPerSec = (effBytesPerMs * 1000) / SIZE_DIVISOR / SIZE_DIVISOR; } // calculate capacity long doneBytes = event.getCapacity() - event.getRemainingCapacity(); long doneTB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR; long doneGB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR % SIZE_DIVISOR; // calculate reading speed (average) long averageBytesPerMs = (doneBytes / 4096) / event.getElapsedTime(); long averageMBPerSec = (averageBytesPerMs * 1000) / SIZE_DIVISOR / SIZE_DIVISOR; previousRemainingCapacity = event.getRemainingCapacity(); previousElapsedTime = event.getElapsedTime(); LOG.info(String.valueOf(percentage) + "% done (" + doneTB + T_UNIT + " " + doneGB + G_UNIT + "), avg.'" + averageMBPerSec + " " + M_UNIT + "/s'" + (effMBPerSec > 0 ? ", eff.'" + effMBPerSec + " " + M_UNIT + "/s'" : "")); } } }); context.addApplicationListener(new ApplicationListener<RoundSingleResultEvent>() { @Override public void onApplicationEvent(RoundSingleResultEvent event) { LOG.info("dl '" + event.getCalculatedDeadline() + "' send (" + (event.isPoolMining() ? "pool" : "solo") + ")"); } }); context.addApplicationListener(new ApplicationListener<RoundSingleResultSkippedEvent>() { @Override public void onApplicationEvent(RoundSingleResultSkippedEvent event) { LOG.info( "dl '" + event.getCalculatedDeadline() + "' > '" + event.getTargetDeadline() + "' skipped"); } }); context.addApplicationListener(new ApplicationListener<NetworkResultConfirmedEvent>() { @Override public void onApplicationEvent(NetworkResultConfirmedEvent event) { LOG.info("dl '" + event.getDeadline() + "' confirmed! [ " + getDeadlineTime(event.getDeadline()) + " ]"); } }); context.addApplicationListener(new ApplicationListener<NetworkDevResultConfirmedEvent>() { @Override public void onApplicationEvent(NetworkDevResultConfirmedEvent event) { LOG.info("devPool response '" + event.getResponse() + "', block '" + event.getBlockNumber() + "'"); for (DevPoolResult devPoolResult : event.getDevPoolResults()) { LOG.info("dl '" + devPoolResult.getCalculatedDeadline() + "' successful committed! [ " + getDeadlineTime(devPoolResult.getCalculatedDeadline()) + " ]"); } } }); context.addApplicationListener(new ApplicationListener<NetworkResultErrorEvent>() { @Override public void onApplicationEvent(NetworkResultErrorEvent event) { LOG.info("strange dl result '" + event.getStrangeDeadline() + "', calculated '" + event.getCalculatedDeadline() + "' " + "block '" + event.getBlockNumber() + "' nonce '" + event.getNonce() + "'"); } }); context.addApplicationListener(new ApplicationListener<ReaderCorruptFileEvent>() { @Override public void onApplicationEvent(ReaderCorruptFileEvent event) { LOG.info("strange dl source '" + event.getFilePath() + "' (try replotting!?)"); LOG.info("strange dl file chunks '" + event.getNumberOfChunks() + "', " + "parts per chunk '" + event.getNumberOfParts() + "', " + "block '" + event.getBlockNumber() + "'"); } }); context.addApplicationListener(new ApplicationListener<ReaderDriveFinishEvent>() { @Override public void onApplicationEvent(ReaderDriveFinishEvent event) { if (blockNumber == event.getBlockNumber()) { // calculate capacity long doneBytes = event.getSize(); long doneTB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR; long doneGB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR % SIZE_DIVISOR; long s = event.getTime() / 1000; long ms = event.getTime() % 1000; LOG.info("read '" + event.getDirectory() + "' (" + doneTB + T_UNIT + " " + doneGB + G_UNIT + ") in '" + s + "s " + ms + "ms'"); } } }); context.addApplicationListener(new ApplicationListener<ReaderDriveInterruptedEvent>() { @Override public void onApplicationEvent(ReaderDriveInterruptedEvent event) { LOG.info("stopped '" + event.getDirectory() + "' for block '" + event.getBlockNumber() + "'."); } }); context.addApplicationListener(new ApplicationListener<NetworkPoolInfoEvent>() { @Override public void onApplicationEvent(NetworkPoolInfoEvent event) { String value = event.getPoolBalanceNQT(); String amount = value.length() > 8 ? value.substring(0, value.length() - 8) : value; value = event.getPoolForgedBalanceNQT(); String totalForget = value.length() > 8 ? value.substring(0, value.length() - 8) : value; LOG.info("-------------------------------------------------------"); LOG.info("POOL account '" + event.getPoolAccountRS() + "', assigned miners '" + event.getPoolNumberOfMiningAccounts() + "'"); LOG.info(" balance '" + amount + " BURST', total mined '" + totalForget + " BURST'"); } }); }
From source file:com.impetus.kundera.ycsb.runner.YCSBRunner.java
public void run(final String workLoad, final int threadCount) throws IOException { int runCounter = crudUtils.getMaxRunSequence(new Date(), runType); runCounter = runCounter + 1;/*from ww w. j a v a 2 s . c om*/ noOfThreads = threadCount; // id column of performanceNoInfo table Date id = new Date(); int counter = 1; for (String client : clients) { currentClient = client; if (clientjarlocation != null && ycsbJarLocation != null && client != null && runType != null && host != null && schema != null && columnFamilyOrTable != null) { Runtime runtime = Runtime.getRuntime(); counter++; String runCommand = getCommandString(client, workLoad); logger.info(runCommand); double totalTime = 0.0; long noOfOperations = 0; Process process = runtime.exec(runCommand); process.getErrorStream(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; BigDecimal avgLatency = null; BigDecimal throughput = null; boolean processed = false; while ((line = br.readLine()) != null) { processed = true; if (line.contains("RunTime")) { totalTime = Double.parseDouble(line.substring(line.lastIndexOf(", ") + 2)); logger.info("Total time taken " + totalTime); } if (line.contains("Operations") && noOfOperations == 0) { noOfOperations = Long.parseLong(line.substring(line.lastIndexOf(", ") + 2)); logger.info("Total no of oprations " + noOfOperations); } if (line.contains("Throughput")) { throughput = new BigDecimal(line.substring(line.lastIndexOf(", ") + 2)); logger.info("Throughput(ops/sec) " + line); } if (line.contains("AverageLatency")) { if (avgLatency == null) { avgLatency = new BigDecimal(line.substring(line.lastIndexOf(", ") + 2)); logger.info("AverageLatency " + line); } } /* * if(line.contains("MinLatency")) { * logger.info("MinLatency " + line); } * if(line.contains("MaxLatency")) { * logger.info("MaxLatency " + line); } */ // if(!(line.contains("CLEANUP") || line.contains("UPDATE") // || line.contains("INSERT") )){ // logger.info(line); // } } if (!processed) { is = process.getErrorStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); line = null; while ((line = br.readLine()) != null) { logger.info(line); } throw new RuntimeException("Error while processing"); } PerformanceNoInfo info = new PerformanceNoInfo(id, releaseNo, client.substring(client.lastIndexOf(".") + 1), runType, noOfThreads, noOfOperations, totalTime, runCounter); if (avgLatency != null) { info.setAvgLatency(avgLatency.round(MathContext.DECIMAL32)); } if (throughput != null) { info.setThroughput(throughput.round(MathContext.DECIMAL32)); } crudUtils.persistInfo(info); timeTakenByClient.put(client, throughput); } } sendMail(); }
From source file:net.pms.util.Rational.java
/** * Converts this {@link Rational} to a {@code float}. This conversion is * similar to the <i>narrowing primitive conversion</i> from {@code double} * to {@code float} as defined in section 5.1.3 of <cite>The Java™ * Language Specification</cite>: if this {@link Rational} has too great a * magnitude to represent as a {@code float}, it will be converted to * {@link Float#NEGATIVE_INFINITY} or {@link Float#POSITIVE_INFINITY} as * appropriate.//from ww w . j a v a 2s . co m * <p> * Note that even when the return value is finite, this conversion can lose * information about the precision of the {@link Rational} value. * * @return This {@link Rational} converted to a {@code float}. */ @Override public float floatValue() { if (isNaN()) { return Float.NaN; } if (isInfinitePositive()) { return Float.POSITIVE_INFINITY; } if (isInfiniteNegative()) { return Float.NEGATIVE_INFINITY; } return new BigDecimal(reducedNumerator).divide(new BigDecimal(reducedDenominator), MathContext.DECIMAL32) .floatValue(); }
From source file:org.apache.calcite.runtime.SqlFunctions.java
/** CAST(FLOAT AS VARCHAR). */ public static String toString(float x) { if (x == 0) { return "0E0"; }/*from w ww . j a v a2s .com*/ BigDecimal bigDecimal = new BigDecimal(x, MathContext.DECIMAL32).stripTrailingZeros(); final String s = bigDecimal.toString(); return s.replaceAll("0*E", "E").replace("E+", "E"); }
From source file:org.multibit.utils.CSMiscUtils.java
public static BigDecimal getDisplayUnitsForRawUnits(CSAsset asset, BigInteger rawQuantity) { if (asset == null) return BigDecimal.ZERO; CoinSparkGenesis genesis = asset.getGenesis(); if (genesis == null) return BigDecimal.ZERO; // This can happen with brand new Manually transferred asset which has not yet been validated. int chargeBasisPoints = genesis.getChargeBasisPoints(); int chargeExponent = genesis.getChargeFlatExponent(); int chargeMantissa = genesis.getChargeFlatMantissa(); int qtyExponent = genesis.getQtyExponent(); int qtyMantissa = genesis.getQtyMantissa(); double interestRate = asset.getInterestRate(); Date issueDate = asset.getIssueDate(); BigDecimal result = new BigDecimal(rawQuantity.toString()); //System.out.println("interest rate = " + interestRate); //System.out.println("issue date = " + issueDate); //System.out.println("raw units =" + result); // 1. Compute interest if (issueDate != null && interestRate != 0.0) { BigDecimal rate = new BigDecimal(String.valueOf(interestRate)); rate = rate.divide(new BigDecimal(100)); rate = rate.add(BigDecimal.ONE); //interestRate = interestRate / 100; //System.out.println("interest rate 1 + ir/100 = " + rate.toPlainString()); // get years elapsed DateTime d1 = new DateTime(issueDate); DateTime d2 = new DateTime(); //System.out.println("Issue: " + d1 + " Now: " + d2); int seconds = Math.abs(Seconds.secondsBetween(d1, d2).getSeconds()); //System.out.println("...Number of seconds difference: " + seconds); BigDecimal elapsedSeconds = new BigDecimal(seconds); //System.out.println("...Number of seconds difference: " + elapsedSeconds.toPlainString()); // To avoid exception, we need to set a precision. // java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. // http://stackoverflow.com/questions/4591206/arithmeticexception-non-terminating-decimal-expansion-no-exact-representable BigDecimal elapsedYears = elapsedSeconds.divide(new BigDecimal(COINSPARK_SECONDS_IN_YEAR), MathContext.DECIMAL32); //System.out.println("...Number of years difference: " + elapsedYears.toPlainString()); double base = elapsedSeconds.doubleValue(); double exp = elapsedYears.doubleValue(); //System.out.println("...base=" + base + " exponent=" + exp); double interestMultipler = Math.pow(rate.doubleValue(), elapsedYears.doubleValue()); //System.out.println("interest multipler =" + interestMultipler); result = result.multiply(new BigDecimal(interestMultipler)); //System.out.println("raw units with interest multiplier =" + result); result = result.setScale(0, RoundingMode.DOWN); //System.out.println("raw units with interest multiplier, floored =" + result); }/*from w w w. j a v a 2 s . com*/ // 2. Apply multiple int decimalPlaces = CSMiscUtils.getNumberOfDisplayDecimalPlaces(asset); BigDecimal display = result; if (decimalPlaces != 0) { // System.out.println(">>>>> display = " + display.toPlainString()); display = result.movePointLeft(decimalPlaces); // System.out.println(">>>>> display = " + display.toPlainString()); } //long qty = Utils.mantissaExponentToQty(qtyMantissa, qtyExponent); // double multiple = asset.getMultiple(); // let's just do it for now to make sure code is corret //if (multiple != 1.0) // BigDecimal m = new BigDecimal(String.valueOf(multiple)); // BigDecimal display = result.multiply(m); //System.out.println("multiplier=" + m + ", display=" + display); // Stripping zeros from internal zero with different scale does not work, so use // JDK bug still seems to exist // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6480539 // http://stackoverflow.com/questions/5239137/clarification-on-behavior-of-bigdecimal-striptrailingzeroes int cmpZeroResult = display.compareTo(BigDecimal.ZERO); if (decimalPlaces == 0) { display = display.stripTrailingZeros(); } // Stripping trailing zeros from internal zero with different scale does not work, so set to ZERO instead. if (0 == cmpZeroResult) { display = BigDecimal.ZERO; } return display; }
From source file:org.multibit.utils.CSMiscUtils.java
public static BigInteger getRawUnitsFromDisplayString(CSAsset asset, String display) { BigDecimal result = null;//from w w w .ja va2 s. co m try { //System.out.println("Start to get raw units from: " + display); result = new BigDecimal(display); } catch (NumberFormatException nfe) { nfe.printStackTrace(); return null; } // Reverse apply the multiple int decimalPlaces = CSMiscUtils.getNumberOfDisplayDecimalPlaces(asset); if (decimalPlaces != 0) { result = result.movePointRight(decimalPlaces); } // FIXME: what if multiple is 0.0? ignore? error? // double multiple = asset.getMultiple(); // BigDecimal m = new BigDecimal(String.valueOf(multiple)); // result = result.divide(m, MathContext.DECIMAL32); //System.out.println("multiplier=" + m + ", removed multiplier =" + display); double interestRate = asset.getInterestRate(); BigDecimal rate = new BigDecimal(String.valueOf(interestRate)); rate = rate.divide(new BigDecimal(100)); rate = rate.add(BigDecimal.ONE); Date issueDate = asset.getIssueDate(); DateTime d1 = new DateTime(issueDate); DateTime d2 = new DateTime(); int seconds = Math.abs(Seconds.secondsBetween(d1, d2).getSeconds()); //System.out.println("...Number of seconds difference: " + seconds); BigDecimal elapsedSeconds = new BigDecimal(seconds); BigDecimal elapsedYears = elapsedSeconds.divide(new BigDecimal(COINSPARK_SECONDS_IN_YEAR), MathContext.DECIMAL32); //System.out.println("...Number of years difference: " + elapsedYears.toPlainString()); double base = elapsedSeconds.doubleValue(); double exp = elapsedYears.doubleValue(); //System.out.println("...base=" + base + " exponent=" + exp); double interestMultipler = Math.pow(rate.doubleValue(), elapsedYears.doubleValue()); //System.out.println("interest multipler =" + interestMultipler); result = result.divide(new BigDecimal(String.valueOf(interestMultipler)), MathContext.DECIMAL32); //System.out.println("result = " + result.toPlainString()); result = result.setScale(0, RoundingMode.DOWN); result = result.stripTrailingZeros(); //System.out.println("result floored = " + result.toPlainString()); String resultString = result.toPlainString(); return new BigInteger(resultString); }