public static String formatByte(long l) { String s = "0 KB"; if (l <= 0x100000L) { BigDecimal bigdecimal = new BigDecimal(l); BigDecimal bigdecimal1 = new BigDecimal(1024); RoundingMode roundingmode = RoundingMode.CEILING; String s1 = String.valueOf(bigdecimal.divide(bigdecimal1, 0, roundingmode).toString()); s = (new StringBuilder(s1)).append(" KB").toString(); } else { if (l >= 0x40000000L) { BigDecimal bigdecimal2 = new BigDecimal(l); BigDecimal bigdecimal3 = new BigDecimal(0x40000000); RoundingMode roundingmode1 = RoundingMode.CEILING; String s2 = String.valueOf(bigdecimal2.divide(bigdecimal3, 2, roundingmode1).toString()); s = (new StringBuilder(s2)).append(" G").toString(); } else { BigDecimal bigdecimal4 = new BigDecimal(l); BigDecimal bigdecimal5 = new BigDecimal(0x100000); RoundingMode roundingmode2 = RoundingMode.CEILING; String s3 = String.valueOf(bigdecimal4.divide(bigdecimal5, 2, roundingmode2).toString()); s = (new StringBuilder(s3)).append(" MB").toString(); } } return s; }
public static ArrayList<BigDecimal> factors(BigDecimal query) { if (query.equals(new BigDecimal("0"))) { return null; } ArrayList<BigDecimal> factors = new ArrayList<BigDecimal>(); BigDecimal sqrt = sqrt(query); if (sqrt.remainder(new BigDecimal("1")).equals(new BigDecimal("0"))) { factors.add(sqrt); } for (float i = 1; i < sqrt.floatValue(); i++) { // simplifying assumption if (factors.size() > 2) { break; } String m = Float.toString(i); BigDecimal otherFactor = query.divide(new BigDecimal(m), MathContext.DECIMAL128); if (query .divide(new BigDecimal(m), MathContext.DECIMAL128) .remainder(new BigDecimal(1)) .floatValue() == 0) { factors.add(new BigDecimal(m)); factors.add(query.divide(new BigDecimal(m))); } } return factors; }
/** * Calculate the mean course grade (whether entered or calulated) as a percentage for all * enrollments, leaving students who've explicitly been given non-percentage-valued manual-only * course grades (such as "I" for incomplete) or null scores out of the calculation. */ public void calculateStatistics(Collection<CourseGradeRecord> gradeRecords, int numEnrollments) { // Ungraded but enrolled students count as if they have 0% in the course. int numScored = numEnrollments - gradeRecords.size(); BigDecimal total = new BigDecimal("0"); BigDecimal average = new BigDecimal("0"); for (CourseGradeRecord record : gradeRecords) { Double score = record.getGradeAsPercentage(); // Skip manual-only course grades. if ((record.getEnteredGrade() != null) && (score == null)) { continue; } if (score != null && record.getPointsEarned() != null) { average = average.add(new BigDecimal(record.getPointsEarned().toString())); total = total.add(new BigDecimal(score.toString())); numScored++; } // numScored++; } if (numScored == 0) { mean = null; averageScore = null; } else { mean = Double.valueOf( total.divide(new BigDecimal(numScored), GradebookService.MATH_CONTEXT).doubleValue()); averageScore = Double.valueOf( average .divide(new BigDecimal(numScored), GradebookService.MATH_CONTEXT) .doubleValue()); } }
public static BigDecimal get(final BigDecimal n) { // Make sure n is a positive number if (n.compareTo(ZERO) <= 0) { throw new IllegalArgumentException(); } final BigDecimal initialGuess = getInitialApproximation(n); BigDecimal lastGuess = ZERO; BigDecimal guess = new BigDecimal(initialGuess.toString()); // Iterate iterations = 0; boolean more = true; while (more) { lastGuess = guess; guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP); guess = guess.add(lastGuess); guess = guess.divide(TWO, scale, BigDecimal.ROUND_HALF_UP); error = n.subtract(guess.multiply(guess)); if (++iterations >= maxIterations) { more = false; } else if (lastGuess.equals(guess)) { more = error.abs().compareTo(ONE) >= 0; } } return guess; }
public static EastNorth getCentroid(List<Node> nodes) { // Compute the centroid of nodes BigDecimal area = new BigDecimal(0); BigDecimal north = new BigDecimal(0); BigDecimal east = new BigDecimal(0); // See http://en.wikipedia.org/w/index.php?title=Centroid&oldid=294224857#Centroid_of_polygon // for the equation used here for (int i = 0; i < nodes.size(); i++) { EastNorth n0 = nodes.get(i).getEastNorth(); EastNorth n1 = nodes.get((i + 1) % nodes.size()).getEastNorth(); BigDecimal x0 = new BigDecimal(n0.east()); BigDecimal y0 = new BigDecimal(n0.north()); BigDecimal x1 = new BigDecimal(n1.east()); BigDecimal y1 = new BigDecimal(n1.north()); BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128)); area = area.add(k, MathContext.DECIMAL128); east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128)); north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128)); } BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3 area = area.multiply(d, MathContext.DECIMAL128); if (area.compareTo(BigDecimal.ZERO) != 0) { north = north.divide(area, MathContext.DECIMAL128); east = east.divide(area, MathContext.DECIMAL128); } return new EastNorth(east.doubleValue(), north.doubleValue()); }
public static String bytes2kb(long bytes) { BigDecimal filesize = new BigDecimal(bytes); BigDecimal megabyte = new BigDecimal(1024 * 1024); float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue(); if (returnValue > 1) return (returnValue + "MB"); BigDecimal kilobyte = new BigDecimal(1024); returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP).floatValue(); return (returnValue + "KB"); }
/** * Ver onde sao guardados os StudentInquiries (QUC): ir por CurricularCourses * * <p>1. Extrair o ED 2. A partir do ED extrair duas collections: CourseResults e TeacherResults * 3. Magia para tirar um score desses results (ainda nao sei o q possa ser esse score. vou * extrair o 'average_NDE' e 'average_P6_1' apenas a titulo de exemplo. nao tem qq valor real. os * values sao em double, passar a BigDecimals e trabalhar sempre neste format). 4. Aplicar 50% à * media do score de todos os CourseResults e 50% à media do score de todos os TeacherResults 5. * Mostrar esse score. */ private String generateQUCResults(YearViewBean bean) { ExecutionDegree executionDegree = ExecutionDegree.getByDegreeCurricularPlanAndExecutionYear( bean.getDegreeCurricularPlan(), bean.getExecutionYear()); Set<StudentInquiriesCourseResult> courseResults = executionDegree.getStudentInquiriesCourseResultsSet(); Set<StudentInquiriesTeachingResult> teachingResults = executionDegree.getStudentInquiriesTeachingResultsSet(); BigDecimal sigmaCR = new BigDecimal(0); BigDecimal cardinalityCR = new BigDecimal(0); BigDecimal averageCR = new BigDecimal(0); BigDecimal sigmaTR = new BigDecimal(0); BigDecimal cardinalityTR = new BigDecimal(0); BigDecimal averageTR = new BigDecimal(0); BigDecimal partialCourse = new BigDecimal(0); BigDecimal partialTeaching = new BigDecimal(0); String result; for (StudentInquiriesCourseResult courseResult : courseResults) { BigDecimal converted = new BigDecimal(courseResult.getAverage_NDE() != null ? courseResult.getAverage_NDE() : 0); sigmaCR = sigmaCR.add(converted); cardinalityCR = cardinalityCR.add(BigDecimal.ONE); } if (cardinalityCR.compareTo(BigDecimal.ZERO) != 0) { averageCR = sigmaCR.divide(cardinalityCR, 4, RoundingMode.HALF_EVEN); } else { averageCR = BigDecimal.ZERO; } for (StudentInquiriesTeachingResult teachingResult : teachingResults) { BigDecimal converted = new BigDecimal( teachingResult.getAverage_P6_1() != null ? teachingResult.getAverage_P6_1() : 0); sigmaTR = sigmaTR.add(converted); cardinalityTR = cardinalityTR.add(BigDecimal.ONE); } if (cardinalityCR.compareTo(BigDecimal.ZERO) != 0) { averageTR = sigmaTR.divide(cardinalityTR, 4, RoundingMode.HALF_EVEN); } else { averageTR = BigDecimal.ZERO; } partialCourse = averageCR.divide(new BigDecimal(2), 2, RoundingMode.HALF_EVEN); partialTeaching = averageTR.divide(new BigDecimal(2), 2, RoundingMode.HALF_EVEN); result = partialCourse.add(partialTeaching).toPlainString(); return result; }
/** * Calculate Grade Factor. Checked against "Introduction to the Scheduler Log" white paper * * @param schedule * @return Grade factor for the schedule */ public BigDecimal calcGrade(ScheduleWrapper schedule) { // 1 - gradeFactor*(1 - rawGradeFactor) BigDecimal sum = new BigDecimal(0, MathContext.DECIMAL32); for (Iterator<Job> it = schedule.getJobs().iterator(); it.hasNext(); ) { Job job = it.next(); Integer iLevel = schedule.getSkillLevel(job.getSkillTypeRef().getId()); if (iLevel == null) { // FIXME: If a job is put on the work schedule, and then the skill for that job is deleted // from the worker, // schedule.getSkillLevel will return null. The job is no longer valid for the work // schedule, and should // be removed. There are two places that this removal should occur: // 1. When the user deletes a skill from a worker, a check should be made to see if any jobs // on the worker's // current schedule have that skill. The user can then decide to abort, or delete the // skill and remove // the jobs from the schedule. // 2. When data is being prepared for the Scheduler, the data should be examined to see if // the person's skills // match the jobs on the schedules for that person, and remove any jobs which require // skills the person // does not have. // // i.e. the fix for invalid data should not be done here. This code just catches the cases // where the data clean // was not performed prior to calling this code. // log( "Worker does not have skill '" + job.getSkillTypeRef().getDescription() + "', though job " + job.getId() + " requires it."); continue; } int schedSkillLevel = iLevel; // # grades worker skill level is over job skill level BigDecimal over = new BigDecimal( schedSkillLevel - job.getSkillLevelRef().getValue(), MathContext.DECIMAL32); // 1 - (over/maxGrade) BigDecimal penalty = new BigDecimal(1).subtract(over.divide(new BigDecimal(maxGrade), MathContext.DECIMAL32)); BigDecimal ptime = new BigDecimal(job.getEstimatedTime().intValue(), MathContext.DECIMAL32); BigDecimal ptimepenalty = ptime.multiply(penalty); sum = sum.add(ptimepenalty); } BigDecimal prodTime = new BigDecimal(schedule.getProductiveTime(), MathContext.DECIMAL32).multiply(ONEHUNDRED); // sum/(scheduleProdTime Hundredths) BigDecimal rawGradeFactor = sum.divide(prodTime, MathContext.DECIMAL32); BigDecimal oneMinusRawGrade = new BigDecimal(1).subtract(rawGradeFactor); BigDecimal result = new BigDecimal(1).subtract(gradeFactor.multiply(oneMinusRawGrade)); return result; }
public static BigDecimal operator_divide(Number x, Number y) { BigDecimal xValue = numberToBigDecimal(x); BigDecimal yValue = numberToBigDecimal(y); if (xValue == null) { return NULL_DEFINITION.divide(yValue, 8, RoundingMode.HALF_UP); } else if (yValue == null) { return xValue.divide(NULL_DEFINITION, 8, RoundingMode.HALF_UP); // throws an exception } else { return xValue.divide(yValue, 8, RoundingMode.HALF_UP); } }
public static BigDecimal sqrt(BigDecimal b) { BigDecimal half = new BigDecimal(1d / 2d); BigDecimal value = b; BigDecimal precision = new BigDecimal(10e-150); while (value .subtract(b.divide(value, 300, RoundingMode.HALF_UP)) .compareTo(precision.multiply(value)) > 0) { value = half.multiply(value.add(b.divide(value, 300, RoundingMode.HALF_UP))); } return value; }
public static MOrderLine createOrderLine( Properties ctx, MOrder order, int productId, BigDecimal qty, BigDecimal discount, BigDecimal lineNet) throws OperationException { if (qty == null) { qty = Env.ONE; } MOrderLine orderLine = new MOrderLine(order); MProduct product = new MProduct(ctx, productId, order.get_TrxName()); MTax tax = TaxManager.getTaxFromCategory(ctx, product.getC_TaxCategory_ID(), order.get_TrxName()); orderLine.setC_Tax_ID(tax.get_ID()); orderLine.setC_UOM_ID(product.getC_UOM_ID()); orderLine.setC_BPartner_ID(order.getC_BPartner_ID()); // Must set Product Id before quantity Ordered. orderLine.setM_Product_ID(productId); orderLine.setQty(qty); orderLine.setPrice(); // Bug fix, set price to 2dp MPriceList orderPriceList = MPriceList.get(ctx, order.getM_PriceList_ID(), order.get_TrxName()); if (!orderPriceList.isTaxIncluded()) { BigDecimal taxAmt = tax.calculateTax(lineNet, true, 12); BigDecimal lineNetWithoutTax = lineNet.subtract(taxAmt); orderLine.setLineNetAmt(lineNetWithoutTax); BigDecimal unitPriceWithoutTax = lineNetWithoutTax.divide(qty, 12, BigDecimal.ROUND_HALF_DOWN); orderLine.setPriceEntered(unitPriceWithoutTax.setScale(2, BigDecimal.ROUND_HALF_UP)); orderLine.setPriceActual(unitPriceWithoutTax.setScale(2, BigDecimal.ROUND_HALF_UP)); } else { BigDecimal unitPrice = lineNet.divide(qty, 12, BigDecimal.ROUND_HALF_DOWN); orderLine.setLineNetAmt(lineNet.setScale(2, BigDecimal.ROUND_HALF_UP)); orderLine.setPriceEntered(unitPrice.setScale(2, BigDecimal.ROUND_HALF_UP)); orderLine.setPriceActual(unitPrice.setScale(2, BigDecimal.ROUND_HALF_UP)); } if (discount.doubleValue() != 0.0) { orderLine.setDiscount(); } PoManager.save(orderLine); return orderLine; }
// Newton's method for sqrt public static BigDecimal sqrt(BigDecimal A, final int SCALE) { BigDecimal x0 = new BigDecimal("0"); BigDecimal x1 = new BigDecimal(Math.sqrt(A.doubleValue())); while (!x0.equals(x1)) { x0 = x1; x1 = A.divide(x0, SCALE, BigDecimal.ROUND_HALF_UP); x1 = x1.add(x0); x1 = x1.divide(TWO, SCALE, BigDecimal.ROUND_HALF_UP); } return x1; }
private CalculCotisationAvsAiApgSalarie( int annee, BigDecimal tauxAVS, BigDecimal tauxAI, BigDecimal tauxAPG) { super(annee); this.tauxAVS = tauxAVS; BigDecimal deux = new BigDecimal(2); this.demiTauxAVS = tauxAVS.divide(deux); this.tauxAI = tauxAI; this.demiTauxAI = tauxAI.divide(deux); this.tauxAPG = tauxAPG; this.demiTauxAPG = tauxAPG.divide(deux); this.tauxTotal = tauxAVS.add(tauxAI).add(tauxAPG); this.demiTauxTotal = demiTauxAVS.add(demiTauxAI).add(demiTauxAPG); }
public static BigDecimal getDistanceFromSpeedAndTime( final BigDecimal speedInMPH, final long timeInMilliseconds) { final BigDecimal timeInSeconds = BigDecimal.valueOf(timeInMilliseconds) .divide(Converter.THOUSAND, Converter.BIGDECIMAL_SCALE, Converter.BIGDECIMAL_ROUNDING); final BigDecimal timeInMinutes = timeInSeconds.divide( Converter.SIXTY, Converter.BIGDECIMAL_SCALE, Converter.BIGDECIMAL_ROUNDING); final BigDecimal timeInHours = timeInMinutes.divide( Converter.SIXTY, Converter.BIGDECIMAL_SCALE, Converter.BIGDECIMAL_ROUNDING); return speedInMPH.multiply(timeInHours); }
public void generarItemCuentaCorriente(MovimientoProveedor m) throws ExcepcionGeneralSistema { if (m.getCondicionDePago() == null) { throw new ExcepcionGeneralSistema("La condición de pago no puede estar vacía"); } if (m.getItemTotal() == null || m.getItemTotal().isEmpty()) { throw new ExcepcionGeneralSistema( "Item total no fue generado, nada para agregar a la cuenta corriente"); } m.getItemCuentaCorriente().clear(); BigDecimal importeTotal = m.getItemTotal().get(0).getImporte(); // // System.err.println("importeTotal para cuenta corriente"+importeTotal); for (ItemCondicionPagoProveedor icp : m.getCondicionDePago().getCuotas()) { BigDecimal impoteCuota = importeTotal.multiply(icp.getPorcentaje()).divide(new BigDecimal(100), RoundingMode.UP); Calendar fechaVencimiento = Calendar.getInstance(); fechaVencimiento.add(Calendar.DAY_OF_YEAR, icp.getDiasDePago()); AplicacionCuentaCorrienteProveedor icc = new AplicacionCuentaCorrienteProveedor(); icc.setMovimiento(m); icc.setMovimientoAplicacion(m); icc.setCuota(icp.getCuotas()); icc.setProveedor(m.getProveedor()); icc.setNroSubcuenta(m.getProveedorCuentaCorriente().getNrocta()); icc.setCodigoImputacion("CC"); icc.setMonedaSecundaria(m.getMonedaSecundaria()); icc.setCotizacion(m.getCotizacion()); if (m.getComprobante().getSignoAplicacionCuentaCorriente().equals("+")) { icc.setImporte(impoteCuota); icc.setImporteSecundario(impoteCuota.divide(m.getCotizacion(), RoundingMode.UP)); } else { icc.setImporte(importeTotal.negate()); icc.setImporteSecundario((impoteCuota.divide(m.getCotizacion(), RoundingMode.UP)).negate()); } icc.setFechaAplicacion(new Date()); icc.setFechaVencimiento(fechaVencimiento.getTime()); m.getItemCuentaCorriente().add(icc); } }
public PercentType[] toRGB() { PercentType red = null; PercentType green = null; PercentType blue = null; BigDecimal h = hue.divide(new BigDecimal(100), 10, BigDecimal.ROUND_HALF_UP); BigDecimal s = saturation.divide(new BigDecimal(100)); int h_int = h.multiply(new BigDecimal(5)) .divide(new BigDecimal(3), 10, BigDecimal.ROUND_HALF_UP) .intValue(); BigDecimal f = h.multiply(new BigDecimal(5)) .divide(new BigDecimal(3), 10, BigDecimal.ROUND_HALF_UP) .remainder(BigDecimal.ONE); PercentType a = new PercentType(value.multiply(BigDecimal.ONE.subtract(s))); PercentType b = new PercentType(value.multiply(BigDecimal.ONE.subtract(s.multiply(f)))); PercentType c = new PercentType( value.multiply(BigDecimal.ONE.subtract((BigDecimal.ONE.subtract(f)).multiply(s)))); if (h_int == 0 || h_int == 6) { red = getBrightness(); green = c; blue = a; } else if (h_int == 1) { red = b; green = getBrightness(); blue = a; } else if (h_int == 2) { red = a; green = getBrightness(); blue = c; } else if (h_int == 3) { red = a; green = b; blue = getBrightness(); } else if (h_int == 4) { red = c; green = a; blue = getBrightness(); } else if (h_int == 5) { red = getBrightness(); green = a; blue = b; } else { throw new RuntimeException(); } return new PercentType[] {red, green, blue}; }
public static void main(String[] args) { BigDecimal f1 = new BigDecimal("0.05"); BigDecimal f2 = BigDecimal.valueOf(0.01); BigDecimal f3 = new BigDecimal(0.05); System.out.println("使用String作为BigDecimal构造器参数:"); System.out.println("0.05 + 0.01 = " + f1.add(f2)); System.out.println("0.05 - 0.01 = " + f1.subtract(f2)); System.out.println("0.05 * 0.01 = " + f1.multiply(f2)); System.out.println("0.05 / 0.01 = " + f1.divide(f2)); System.out.println("使用double作为BigDecimal构造器参数:"); System.out.println("0.05 + 0.01 = " + f3.add(f2)); System.out.println("0.05 - 0.01 = " + f3.subtract(f2)); System.out.println("0.05 * 0.01 = " + f3.multiply(f2)); System.out.println("0.05 / 0.01 = " + f3.divide(f2)); }
public int getTechValue() { // Make sure we have units. if (getNumberUnits().compareTo(BigDecimal.ZERO) == 0) { return 0; } // Number of high-tech units is equal to the number of IS2 units plus twice the number of Clan // units. BigDecimal highTechNumber = new BigDecimal(getCountIS2() + (getCountClan() * 2)); // Conventional infantry does not count. int numberUnits = getFighterCount() + getNumberBaSquads() + getMechCount() + getLightVeeCount() + getNumberOther(); if (numberUnits <= 0) { return 0; } // Calculate the percentage of high-tech units. setHighTechPercent(highTechNumber.divide(new BigDecimal(numberUnits), PRECISION, HALF_EVEN)); setHighTechPercent(getHighTechPercent().multiply(ONE_HUNDRED)); // Cannot go above 100 percent. if (getHighTechPercent().compareTo(ONE_HUNDRED) > 0) { setHighTechPercent(ONE_HUNDRED); } // Score is calculated from percentage above 30%. BigDecimal scoredPercent = getHighTechPercent().subtract(new BigDecimal(30)); // If we have a negative value (hi-tech percent was < 30%) return a value of zero. if (scoredPercent.compareTo(BigDecimal.ZERO) <= 0) { return 0; } // Round down to the nearest whole percentage. scoredPercent = scoredPercent.setScale(0, RoundingMode.DOWN); // Add +5 points for every 10% remaining. BigDecimal oneTenth = scoredPercent.divide(new BigDecimal(10), PRECISION, HALF_EVEN); BigDecimal score = oneTenth.multiply(new BigDecimal(5)); return score.intValue(); }
private void obtenerPrecio(java.math.BigDecimal valorRetorno) { java.math.BigDecimal parcial = new java.math.BigDecimal(valorRetorno == null ? "0.00" : valorRetorno.toString().trim()); java.math.BigDecimal cantidad = new java.math.BigDecimal( tabla.getValueAt(fila, buscarColumna("Cantidad", tabla)).toString().trim().isEmpty() ? "1.00" : tabla.getValueAt(fila, buscarColumna("Cantidad", tabla)).toString().trim()); java.math.BigDecimal precio = parcial.divide(cantidad, 15, java.math.RoundingMode.HALF_EVEN); java.math.BigDecimal porcentaje = new java.math.BigDecimal( tabla.getValueAt(fila, buscarColumna("%", tabla)).toString().trim().isEmpty() ? "1.00" : tabla.getValueAt(fila, buscarColumna("%", tabla)).toString().trim()); java.math.BigDecimal valorPorcentaje = parcial.multiply(porcentaje).divide(new java.math.BigDecimal("100.00")); java.math.BigDecimal valorsubTotal = parcial.subtract(valorPorcentaje); tabla.setValueAt(precio, fila, buscarColumna("Precio", tabla)); tabla.setValueAt(valorPorcentaje, fila, buscarColumna("Descuento", tabla)); tabla.setValueAt(valorsubTotal, fila, buscarColumna("Subtotal", tabla)); tabla.updateUI(); }
private static BigInteger getNearby(BigInteger significand, int binExp, int offset) { int nExtraBits = 1; int nDec = (int) Math.round(3.0 + (64 + nExtraBits) * Math.log10(2.0)); BigInteger newFrac = significand.shiftLeft(nExtraBits).add(BigInteger.valueOf(offset)); int gg = 64 + nExtraBits - binExp - 1; BigDecimal bd = new BigDecimal(newFrac); if (gg > 0) { bd = bd.divide(new BigDecimal(BigInteger.ONE.shiftLeft(gg))); } else { BigInteger frac = newFrac; while (frac.bitLength() + binExp < 180) { frac = frac.multiply(BigInteger.TEN); } int binaryExp = binExp - newFrac.bitLength() + frac.bitLength(); bd = new BigDecimal(frac.shiftRight(frac.bitLength() - binaryExp - 1)); } int excessPrecision = bd.precision() - nDec; if (excessPrecision > 0) { bd = bd.setScale(bd.scale() - excessPrecision, BigDecimal.ROUND_HALF_UP); } return bd.unscaledValue(); }
/** * Calculate Used Time. Checked against "Introduction to the Scheduler Log" white paper * * @param schedule * @return Used time */ public BigDecimal usedTime(ScheduleWrapper schedule) { // productiveTime / totalTime BigDecimal productive = new BigDecimal(schedule.getProductiveTime(), MathContext.DECIMAL32); BigDecimal divisor = new BigDecimal(schedule.getTotalTime(), MathContext.DECIMAL32); BigDecimal result = productive.divide(divisor, MathContext.DECIMAL32); return result; }
private static JsonValue decimalEval(JsonNumber v1, JsonNumber v2, int op) { BigDecimal n1 = v1.decimalValue(); BigDecimal n2 = v2.decimalValue(); BigDecimal n3; switch (op) { case PLUS: { n3 = n1.add(n2, MathContext.DECIMAL128); break; } case MINUS: { n3 = n1.subtract(n2, MathContext.DECIMAL128); break; } case MULTIPLY: { n3 = n1.multiply(n2, MathContext.DECIMAL128); break; } case DIVIDE: { try { n3 = n1.divide(n2, MathContext.DECIMAL128); } catch (ArithmeticException e) { // TODO: need +INF, -INF, and NaN return null; } break; } default: throw new RuntimeException("invalid op:" + op); } return new JsonDecimal(n3); }
private BigDecimal popResult() { if (operand1 == null || operand2 == null || operation == null) { clear(); return ZERO; } BigDecimal result = null; switch (operation) { case PLUS: result = operand2.add(operand1); break; case MINUS: result = operand2.subtract(operand1); break; case MULTIPLY: result = operand2.multiply(operand1); break; case DIVIDE: try { result = operand2.divide(operand1, DECIMAL32); } catch (ArithmeticException e) { result = ZERO; } break; default: throw new IllegalStateException(); } clearOnDigit = true; negativeNumber = false; operand1 = result; operand2 = null; operation = null; return result; }
public BigDecimal previsao(BigDecimal total, String periodo) { BigDecimal diaUteis = BigDecimal.ONE; int diasUlteisTotal = diasUteis(true, periodo); int diasUlteisDecorridos = diasUteis(false, periodo); if (diasUlteisDecorridos < 2) { return BigDecimal.ZERO; } else { diaUteis = new BigDecimal(diasUlteisDecorridos); diaUteis = diaUteis.subtract(BigDecimal.ONE); } BigDecimal mediaDiaria; if (total != null) { mediaDiaria = total.divide( diaUteis.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ONE : diaUteis, 2, RoundingMode.HALF_UP); } else { mediaDiaria = BigDecimal.ZERO; } return mediaDiaria.multiply(new BigDecimal(diasUlteisTotal)); }
public static void main(String[] args) throws ParseException { // ZoneId america = ZoneId.of("America/New_York"); // ZoneId zone0 = ZoneId.of("UTC+00:00"); // ZoneId zone8 = ZoneId.of("UTC+08:00"); // ZoneOffset offset = ZoneOffset.UTC; // LocalDateTime nowOfHere = LocalDateTime.now(); // ZonedDateTime timePoint8 =ZonedDateTime.of(nowOfHere, zone8); // ZonedDateTime timePoint0 = timePoint8.withZoneSameInstant(zone0); // // System.out.println(timePoint8); // System.out.println(timePoint0); double f1 = 299.0F / 31; double f2 = f1 * 31; System.out.println(f1); System.out.println(f2); System.out.println(f2 == 299.0d); if (f2 - 299.0 < 0.0001) { System.out.println("equals"); } BigDecimal bd1 = new BigDecimal(299); BigDecimal bd2 = bd1.divide(new BigDecimal(31), 5, BigDecimal.ROUND_CEILING); BigDecimal bd3 = bd2.multiply(new BigDecimal(31)); System.out.println(bd1); System.out.println(bd2); System.out.println(bd3); System.out.println(bd1.equals(bd3)); }
/** * The allowed amount to stretch the top or bottom end of the overall bin range in order to reach * 'nicer' inward extreme values. * * <p>This is currently defined as the ideal bin width (range / binCount) X 1/2, rounded up. * * @param range The range is expected to be positive. * @return */ protected static BigDecimal getAllowedInwardRangeStretch(BigDecimal range, int binCount) { BigDecimal allowedRangeStretch = range.divide(new BigDecimal(2 * binCount), new MathContext(16, RoundingMode.UP)); return allowedRangeStretch; }
/** * 전체 실행건수 대비 오류 발생 비율을 계산하여 기준에 따라 감점 * * @return returnVal 감점 점수 */ public int getErrExePoint() { int returnVal = 0; if (getTotExeCnt() == 0) { return returnVal; } // 전체 실행건수 대비 오류발생 건수 비율을 소수점 2자리까지 표현 BigDecimal errExeCount = new BigDecimal(getErrExeCnt() + ".00"); BigDecimal totExeCount = new BigDecimal(getTotExeCnt() + ".00"); BigDecimal val = errExeCount.divide(totExeCount, 3).multiply(new BigDecimal(100)); if (val.doubleValue() == 0) { returnVal = 50; } else if (val.doubleValue() < 0.05) { returnVal = -10; } else if (val.doubleValue() < 0.10) { returnVal = -30; } else if (val.doubleValue() < 0.15) { returnVal = -60; } else if (val.doubleValue() < 0.30) { returnVal = -100; } else if (val.doubleValue() < 0.50) { returnVal = -150; } else if (val.doubleValue() < 1) { returnVal = -250; } else if (val.doubleValue() < 2) { returnVal = -400; } else { returnVal = -600; } return returnVal; }
/** * Metoda dodająca ocenę * * @param id_ksiazka id książki wskazanej przez użytkownika * @param wartosc wartość oceny jaką wskazał użytkownia (1-5) * @param login login użytkownika który ocenia książkę. * @throws UzytkownikException jeśli użytkownik nie istnieje * @throws OcenaException jeśli ocena JUŻ istnieje * @throws KsiazkaException jeśli książka została zmodyfikowana podczas oceny (OptimistickLock). */ @RolesAllowed("DodanieOceny") @Override public void ocenKsiazke(long id_ksiazka, int wartosc, String login) throws UzytkownikException, OcenaException, KsiazkaException, AutorException { Ocena ocena = new Ocena(); ocena.setIdKsiazka(ksiazkaFacade.find(id_ksiazka)); ocena.setIdUzytkownik(uzytkownikFacade.findByLogin(login)); ocena.setOcena(wartosc); ocena.setUlubiona(false); ocenaFacade.create(ocena); long suma = 0; for (Ocena o : ocena.getIdKsiazka().getOcenaList()) { suma = suma + o.getOcena(); } ocena .getIdKsiazka() .setSredniaOcen(new BigDecimal((double) suma / ocena.getIdKsiazka().getOcenaList().size())); ksiazkaFacade.edit(ocena.getIdKsiazka()); for (Autor a : ocena.getIdKsiazka().getAutorList()) { BigDecimal licznik = BigDecimal.ZERO; BigDecimal mianownik = BigDecimal.ZERO; for (Ksiazka k : a.getKsiazkaList()) { if (k.getSredniaOcen() != null) { mianownik = mianownik.add(BigDecimal.valueOf(1.0 / (k.getIloscAutorow()))); licznik = licznik.add( k.getSredniaOcen().multiply(BigDecimal.valueOf(1.0 / k.getIloscAutorow()))); } } a.setSrOcena(licznik.divide(mianownik, new MathContext(10))); autorFacade.edit(a); } }
// Gauss-Legendre Algorithm public static BigDecimal calculatePi() { BigDecimal a = ONE; BigDecimal b = ONE.divide(sqrt(TWO, SCALE), SCALE, BigDecimal.ROUND_HALF_UP); BigDecimal t = new BigDecimal(0.25); BigDecimal x = ONE; BigDecimal y; while (!a.equals(b)) { y = a; // a = (a + b)/2 a = a.add(b).divide(TWO, SCALE, BigDecimal.ROUND_HALF_UP); // b = sqrt(b*y) b = sqrt(b.multiply(y), SCALE); // t -= x*((y - a)^2) t = t.subtract(x.multiply(y.subtract(a).multiply(y.subtract(a)))); // x *= 2 x = x.multiply(TWO); } // a + (a+b)/(4) return a.add(b).multiply(a.add(b)).divide(t.multiply(FOUR), SCALE, BigDecimal.ROUND_HALF_UP); }
/** * 전체 실행건수 대비 2000ms 이상 실행 건수 비율을 계산하여 기준에 따라 감점 * * @return returnVal 감점 점수 */ public int getLongExePoint() { int returnVal = 0; if (getTotExeCnt() == 0) { return returnVal; } // 전체 실행건수 대비 2000ms 이상 실행 건수 비율을 소수점 2자리까지 표현 BigDecimal longExeCount = new BigDecimal(getLongExeCnt() + ".00"); BigDecimal totExeCount = new BigDecimal(getTotExeCnt() + ".00"); BigDecimal val = longExeCount.divide(totExeCount, 3).multiply(new BigDecimal(100)); if (val.doubleValue() == 0) { returnVal = 50; } else if (val.doubleValue() < 0.05) { returnVal = -5; } else if (val.doubleValue() < 0.10) { returnVal = -15; } else if (val.doubleValue() < 0.3) { returnVal = -30; } else if (val.doubleValue() < 0.6) { returnVal = -50; } else if (val.doubleValue() < 1) { returnVal = -75; } else if (val.doubleValue() < 2) { returnVal = -125; } else if (val.doubleValue() < 4) { returnVal = -200; } else { returnVal = -300; } return returnVal; }