List of usage examples for java.math RoundingMode UP
RoundingMode UP
To view the source code for java.math RoundingMode UP.
Click Source Link
From source file:com.tencent.wetest.common.util.DeviceUtil.java
public static String getCpuMinFreq() { String result = "--"; double cpuMinFreq = 0; try {/*from w w w.j a va 2 s . c om*/ BufferedReader br = new BufferedReader( new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq")); String text = ""; while ((text = br.readLine()) != null) { text = text.trim(); if (!"".equals(text.trim())) { cpuMinFreq = Double.parseDouble(text.trim()) / (1000 * 1000); BigDecimal bg = new BigDecimal(cpuMinFreq).setScale(2, RoundingMode.UP); result = "" + bg.doubleValue(); // DeviceUtil.cpuMinFreq = cpuMinFreq; } break; } br.close(); br = null; } catch (Exception e) { Logger.error("getCpuMinFreqException" + e.toString()); } return result; }
From source file:org.micromanager.plugins.magellan.autofocus.CrossCorrelationAutofocus.java
/** * Called by acquisitions at then end of time point * @param timeIndex /*from ww w . j a v a 2 s. c o m*/ */ public void run(int timeIndex) throws Exception { Log.log("________", true); Log.log("Autofocus for acq " + acq_.getName() + " Time point " + timeIndex, true); if (timeIndex == 0) { //get initial position try { currentPosition_ = initialPosition_; previousPosition_ = initialPosition_; } catch (Exception e) { Log.log("Couldn't get autofocus Z drive initial position", true); } //figure out which resolution level will be used for xCorr MultiResMultipageTiffStorage storage = acq_.getStorage(); //do these calulations with BigIntegers to prevent overflow and Nan values BigInteger tileWidth = new BigInteger(storage.getTileWidth() + ""); BigInteger tileHeight = new BigInteger(storage.getTileHeight() + ""); BigInteger numCols = new BigInteger(acq_.getNumColumns() + ""); BigInteger numRows = new BigInteger(acq_.getNumRows() + ""); //figure out how much downsampling needed to run autofocus in a reasonable amount of time //factor of two is for z padding BigDecimal numPix2D = new BigDecimal( tileWidth.multiply(numCols).multiply(tileHeight).multiply(numRows)); BigDecimal numXCorrSlices = new BigDecimal((acq_.getNumSlices()) + ""); double dsFactor = //ratio of number of voxels to voxel target Math.sqrt(numPix2D.multiply(numXCorrSlices) .divide(new BigDecimal((double) NUM_VOXEL_TARGET), RoundingMode.UP).doubleValue()); downsampleIndex_ = (int) Math.max(0, Math.round(Math.log(dsFactor) / Math.log(2))); downsampledWidth_ = (int) (tileWidth.multiply(numCols).longValue() / Math.pow(2, downsampleIndex_)); downsampledHeight_ = (int) (tileHeight.multiply(numRows).longValue() / Math.pow(2, downsampleIndex_)); Log.log("Drift compensation DS Index: " + downsampleIndex_, false); Log.log("Drift compensation DS Width: " + downsampledWidth_, false); Log.log("Drift compensation DS Height: " + downsampledHeight_, false); } else { ImageStack lastTPStack = createAFStack(acq_, timeIndex - 1, channelIndex_, downsampledWidth_, downsampledHeight_, downsampleIndex_); ImageStack currentTPStack = createAFStack(acq_, timeIndex, channelIndex_, downsampledWidth_, downsampledHeight_, downsampleIndex_); //run autofocus //image drift is the difference between this TP and the previous one //but does not represent the acutal drift because these 2 TPs will likely have different //positions for the AF compensation Z device //drifteCorrection = move for the AF drive to bring current TP to position of previous TP double driftCorrection = -calcFocusDrift(acq_.getName(), lastTPStack, currentTPStack, acq_.getZStep()); Log.log(acq_.getName() + " Drift compensation: correction = " + driftCorrection, true); //now add in a factor accounting for the previous AF //i.e. how far the reference image is from the desired position driftCorrection += (currentPosition_ - previousPosition_); Log.log(acq_.getName() + " Drift compensation: correction (accounting for previous position) = " + driftCorrection, true); //check if outside max displacement if (Math.abs(currentPosition_ + driftCorrection - initialPosition_) > maxDisplacement_) { Log.log("Calculated focus drift of " + driftCorrection + " um exceeds tolerance. Leaving autofocus offset unchanged", true); return; } Log.log("New position: " + (currentPosition_ + driftCorrection), true); previousPosition_ = currentPosition_; currentPosition_ += driftCorrection; } }
From source file:com.tencent.wetest.common.util.DeviceUtil.java
public static String getCpuMaxFreq() { String result = "--"; double cpuMaxFreq = 0; try {//from www . jav a 2 s .c o m BufferedReader br = new BufferedReader( new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq")); String text = ""; while ((text = br.readLine()) != null) { text = text.trim(); if (!"".equals(text.trim())) { cpuMaxFreq = Double.parseDouble(text.trim()) / (1000 * 1000); BigDecimal bg = new BigDecimal(cpuMaxFreq).setScale(1, RoundingMode.UP); result = "" + bg.doubleValue(); } break; } br.close(); br = null; } catch (Exception e) { Logger.error("getCpuMaxFreq Exception:" + e.toString()); } return result; }
From source file:edu.synth.state.SyntHelperState.java
public void handleObsData() throws IOException { File obsFile = new File(Constants.OBS_DATA); TreeMap<Double, Double> obs = FileWorker.getSortedDoubleData(obsFile); synthSettings.setStartSynth(new BigDecimal(obs.firstKey()).setScale(0, RoundingMode.DOWN).intValue()); synthSettings.setEndSynth(new BigDecimal(obs.lastKey()).setScale(0, RoundingMode.UP).intValue()); List<String> strs = new ArrayList<String>(); for (Entry<Double, Double> ent : obs.entrySet()) strs.add(String.format(Locale.ENGLISH, "%1.4f %1.4f", ent.getKey(), ent.getValue())); FileWorker.write(obsFile, strs);/* ww w . ja va 2s .c o m*/ }
From source file:net.groupbuy.plugin.PaymentPlugin.java
/** * ?//from www. jav a2s .c o m * * @param amount * ? * @return ? */ public BigDecimal calculateAmount(BigDecimal amount) { return amount.add(calculateFee(amount)).setScale(2, RoundingMode.UP); }
From source file:org.apache.sling.reqanalyzer.impl.RequestAnalyzerWebConsole.java
private String formatByteSize(final long value) { final String suffix; final String suffixedValue; if (value >= 0) { final BigDecimal KB = new BigDecimal(1000L); final BigDecimal MB = new BigDecimal(1000L * 1000); final BigDecimal GB = new BigDecimal(1000L * 1000 * 1000); BigDecimal bd = new BigDecimal(value); if (bd.compareTo(GB) > 0) { bd = bd.divide(GB);//from www . ja va 2 s. c o m suffix = "GB"; } else if (bd.compareTo(MB) > 0) { bd = bd.divide(MB); suffix = "MB"; } else if (bd.compareTo(KB) > 0) { bd = bd.divide(KB); suffix = "kB"; } else { suffix = "B"; } suffixedValue = bd.setScale(2, RoundingMode.UP).toString(); } else { suffixedValue = "n/a"; suffix = ""; } return suffixedValue + suffix; }
From source file:org.openvpms.archetype.rules.supplier.OrderGenerator.java
/** * Creates a {@link Stock} from {@code set}, if stock needs to be ordered. * * @param set the object set * @param product the product * @param supplier the product supplier * @param stockLocation the product stock location * @param belowIdealQuantity if {@code true}, create stock if the current quantity {@code <=} the ideal quantity, * create stock if the current quantity {@code <=} the critical quantity * @return the stock, or {@code null} if the requirements for ordering the stock aren't met *///from www .j a v a2 s . c om private Stock getStock(ObjectSet set, Product product, Party supplier, Party stockLocation, boolean belowIdealQuantity) { Stock stock = null; long productSupplierId = set.getLong("productSupplierId"); BigDecimal quantity = getDecimal("quantity", set); BigDecimal idealQty = getDecimal("idealQty", set); BigDecimal criticalQty = getDecimal("criticalQty", set); int packageSize = set.getInt("packageSize"); String packageUnits = set.getString("packageUnits"); String reorderCode = set.getString("reorderCode"); String reorderDesc = set.getString("reorderDesc"); BigDecimal nettPrice = getDecimal("nettPrice", set); BigDecimal listPrice = getDecimal("listPrice", set); BigDecimal orderedQty = getDecimal("orderedQty", set); BigDecimal receivedQty = getDecimal("receivedQty", set); BigDecimal cancelledQty = getDecimal("cancelledQty", set); if (packageSize != 0) { BigDecimal decSize = BigDecimal.valueOf(packageSize); BigDecimal onOrder; if (receivedQty.compareTo(orderedQty) > 0) { onOrder = receivedQty; } else { onOrder = orderedQty.subtract(receivedQty).subtract(cancelledQty); } BigDecimal current = quantity.add(onOrder); // the on-hand and on-order stock BigDecimal toOrder = ZERO; BigDecimal units = idealQty.subtract(current); // no. of units required to get to idealQty if (!MathRules.equals(ZERO, units)) { // Round up as the desired no. may be less than a packageSize, but must order a whole pack. toOrder = units.divide(decSize, 0, RoundingMode.UP); } if (log.isDebugEnabled()) { log.debug("Stock: product=" + product.getName() + " (" + product.getId() + "), location=" + stockLocation.getName() + " (" + stockLocation.getId() + "), supplier=" + supplier.getName() + " (" + supplier.getId() + "), onHand=" + quantity + ", onOrder=" + onOrder + ", toOrder=" + toOrder + ", idealQty=" + idealQty + ", criticalQty=" + criticalQty); } if (!MathRules.equals(ZERO, toOrder) && (belowIdealQuantity && current.compareTo(idealQty) <= 0 || (current.compareTo(criticalQty) <= 0))) { stock = new Stock(product, stockLocation, supplier, productSupplierId, quantity, idealQty, onOrder, toOrder, reorderCode, reorderDesc, packageSize, packageUnits, nettPrice, listPrice); } } else { if (log.isDebugEnabled()) { log.debug("Cannot order product=" + product.getName() + " (" + product.getId() + ") at location=" + stockLocation.getName() + " (" + stockLocation.getId() + ") from supplier=" + supplier.getName() + " (" + supplier.getId() + ") - no package size"); } } return stock; }
From source file:br.com.fidias.chance4j.Chance.java
/** * Return a random BigDecimal number.//from w w w .j a v a 2 s. c o m * <pre> * chance.getBigDecimal(-10, 100, 2); * => 45.89 * </pre> * * @param min Minimum value to choose from * @param max Maximum value to choose from * @param fixed Specify a fixed precision * @return A random BigDecimal * @throws ChanceException */ public BigDecimal getBigDecimal(Integer min, Integer max, int fixed) throws ChanceException { if (min != null && max != null && max < min) { throw new ChanceException("Max must be greater than min."); } int num; int localFixed = (int) Math.pow(10, fixed + FORCE_INCREASE_FIXED); int localMax = (int) (Integer.MAX_VALUE / localFixed); int localMin = -localMax; if (max == null) { max = localMax; } else if (max > localMax) { final String message = "Max specified (%d) is out of range with fixed. " + "Max should be, at most, %d"; throw new ChanceException(String.format(message, max, localMax)); } if (min == null) { min = localMin; } else if (min < localMin) { final String message = "Min specified (%d) is out of range with fixed. " + "Min should be, at least, %d"; throw new ChanceException(String.format(message, min, localMin)); } num = integer(min * localFixed, max * localFixed); BigDecimal bd = new BigDecimal(num).divide(new BigDecimal(localFixed), MathContext.UNLIMITED); return bd.setScale(fixed, RoundingMode.UP); }
From source file:petascope.wcps2.util.CrsComputer.java
/** * Returns the translated subset for regular axis * * @param numericSubset the numeric subset to be translated * @return//from ww w.j av a 2 s . co m */ private Interval<Long> getNumericPixelIndicesForRegularAxis(Interval<Double> numericSubset) { boolean zeroIsMin = coverage.getCoverageMetadata().getDomainDirectionalResolution(axisName) .doubleValue() > 0; DomainElement dom = coverage.getCoverageInfo().getDomainByName(axisName); CellDomainElement cdom = coverage.getCoverageInfo().getCellDomainByName(axisName); String axisUoM = dom.getUom(); // Get Domain extremes (real sdom) BigDecimal domMin = dom.getMinValue(); BigDecimal domMax = dom.getMaxValue(); long pxMin = cdom.getLoInt(); long pxMax = cdom.getHiInt(); // Indexed CRSs do not require conversion if (crsName == CrsUtil.GRID_CRS) { return new Interval<Long>((long) numericSubset.getLowerLimit().doubleValue(), (long) numericSubset.getUpperLimit().doubleValue()); } // This part is copied over from CRSUtil.java verbatim TODO: refactor the whole CRS computer ASAP // Indexed CRSs (integer "GridSpacing" UoM): no need for math proportion, coords are just int offsets. // This is not the same as CRS:1 which access direct grid coordinates. // Index CRSs have indexed coordinates, but still offset vectors can determine a different reference (eg origin is UL corner). if (axisUoM.equals(CrsUtil.INDEX_UOM)) { int count = 0; long indexMin = cdom.getLoInt(); long indexMax = cdom.getHiInt(); // S = subset value, px_s = subset grid index // m = min(grid index), M = max(grid index) // {isPositiveForwards / isNegativeForwards} // Formula : px_s = grid_origin + [{S/M} - {m/S}] long[] subsetGridIndexes = new long[2]; for (String subset : (Arrays.asList(new String[] { numericSubset.getLowerLimit().toString(), numericSubset.getUpperLimit().toString() }))) { // NOTE: on subsets.lo the /next/ integer needs to be taken : trunc(stringLo) + 1 (if it is not exact integer) boolean roundUp = subset.equals(numericSubset.getLowerLimit().toString()) && ((double) Double.parseDouble(subset) != (long) Double.parseDouble(subset)); long hiBound = dom.isPositiveForwards() ? (long) Double.parseDouble(subset) + (roundUp ? 1 : 0) : indexMax; long loBound = dom.isPositiveForwards() ? indexMin : (long) Double.parseDouble(subset) + (roundUp ? 1 : 0); subsetGridIndexes[count] = domMin.longValue() + (hiBound - loBound); count += 1; } // if offset is negative, the limits are inverted if (subsetGridIndexes[0] > subsetGridIndexes[1]) { return new Interval<Long>(subsetGridIndexes[1], subsetGridIndexes[0]); } return new Interval<Long>(subsetGridIndexes[0], subsetGridIndexes[1]); } BigDecimal cellWidth = (domMax.subtract(domMin)) .divide((BigDecimal.valueOf(pxMax + 1)).subtract(BigDecimal.valueOf(pxMin)), RoundingMode.UP); // Open interval on the right: take away epsilon from upper bound: long returnLowerLimit, returnUpperLimit; if (zeroIsMin) { // Normal linear numerical axis returnLowerLimit = (long) Math.floor(BigDecimalUtil .divide(BigDecimal.valueOf(numericSubset.getLowerLimit()).subtract(domMin), cellWidth) .doubleValue()) + pxMin; if (numericSubset.getUpperLimit().equals(numericSubset.getLowerLimit())) { returnUpperLimit = returnLowerLimit; } else { returnUpperLimit = (long) Math.ceil(BigDecimalUtil .divide(BigDecimal.valueOf(numericSubset.getUpperLimit()).subtract(domMin), cellWidth) .doubleValue()) - 1 + pxMin; } // NOTE: the if a slice equals the upper bound of a coverage, out[0]=pxHi+1 but still it is a valid subset. if (numericSubset.getLowerLimit() == numericSubset.getUpperLimit() && numericSubset.getUpperLimit() == domMax.doubleValue()) { returnLowerLimit = returnLowerLimit - 1; } } else { // Linear negative axis (eg northing of georeferenced images) // First coordHi, so that left-hand index is the lower one returnLowerLimit = (long) Math.ceil(BigDecimalUtil .divide(domMax.subtract(BigDecimal.valueOf(numericSubset.getUpperLimit())), cellWidth) .doubleValue()) + pxMin; if (numericSubset.getUpperLimit() == numericSubset.getLowerLimit()) { returnUpperLimit = returnLowerLimit; } else { returnUpperLimit = (long) Math.floor(BigDecimalUtil .divide(domMax.subtract(BigDecimal.valueOf(numericSubset.getLowerLimit())), cellWidth) .doubleValue()) - 1 + pxMin; } // NOTE: the if a slice equals the lower bound of a coverage, out[0]=pxHi+1 but still it is a valid subset. if (numericSubset.getLowerLimit() == numericSubset.getUpperLimit() && numericSubset.getUpperLimit() == domMin.doubleValue()) { returnLowerLimit -= 1; } } return new Interval<Long>(returnLowerLimit, returnUpperLimit); }
From source file:org.openhab.binding.denon.internal.DenonConnector.java
private String toDenonValue(BigDecimal percent) { // Round to nearest number divisible by 0.5 percent = percent.divide(POINTFIVE).setScale(0, RoundingMode.UP).multiply(POINTFIVE) .min(connection.getMainVolumeMax()).max(BigDecimal.ZERO); String dbString = String.valueOf(percent.intValue()); if (percent.compareTo(BigDecimal.TEN) == -1) { dbString = "0" + dbString; }//from w ww . j ava2 s .c o m if (percent.remainder(BigDecimal.ONE).equals(POINTFIVE)) { dbString = dbString + "5"; } return dbString; }