Example usage for java.math BigDecimal divide

List of usage examples for java.math BigDecimal divide

Introduction

In this page you can find the example usage for java.math BigDecimal divide.

Prototype

public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , and whose scale is as specified.

Usage

From source file:org.egov.egf.web.actions.budget.BudgetSearchAction.java

public BigDecimal divideAndRoundStrToBigDec(final String amountStr) {
    BigDecimal value = new BigDecimal(amountStr);
    value = value.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
    return value;
}

From source file:de.tudarmstadt.ukp.dkpro.keyphrases.core.evaluator.util.KeyphrasePerformanceCounter.java

public Double getMeanAveragePrecision() {
    BigDecimal meanAveragePrecision = new BigDecimal("0.0");
    for (FilePerformance filePerformance : fileName2performanceMap.values()) {
        meanAveragePrecision = meanAveragePrecision.add(filePerformance.calculateAveragePrecision());
    }//from   ww  w. j  a v  a 2  s  .c  o m
    if (fileName2performanceMap.size() == 0) {
        return 0d;
    }
    meanAveragePrecision = meanAveragePrecision.divide(
            new BigDecimal(String.valueOf(fileName2performanceMap.size())), NBR_FLOATING_POINTS,
            RoundingMode.UP);
    return meanAveragePrecision.doubleValue();
}

From source file:org.yes.cart.service.domain.impl.ImageServiceImpl.java

int[] cropImageToCenter(final int targetX, final int targetY, final int originalX, final int originalY) {

    // calculate crop so that we can scale to fit
    BigDecimal sourceRatio = new BigDecimal(originalX).divide(new BigDecimal(originalY), 10,
            BigDecimal.ROUND_HALF_UP);
    BigDecimal targetRatio = new BigDecimal(targetX).divide(new BigDecimal(targetY), 10,
            BigDecimal.ROUND_HALF_UP);
    final int cropWidth, cropHeight, cropX, cropY;
    if (sourceRatio.compareTo(targetRatio) < 0) { // need to crop by height
        cropWidth = originalX;/*w  w w  .  j av a 2s . c o m*/
        cropHeight = new BigDecimal(originalY)
                .divide((targetRatio.divide(sourceRatio, 10, BigDecimal.ROUND_HALF_UP)), 0,
                        BigDecimal.ROUND_HALF_UP)
                .intValue();
        cropX = 0;
        cropY = (originalY - cropHeight) / 2;
    } else { // need to crop by width
        cropHeight = originalY;
        cropWidth = new BigDecimal(originalX)
                .divide((sourceRatio.divide(targetRatio, 10, BigDecimal.ROUND_HALF_UP)), 0,
                        BigDecimal.ROUND_HALF_UP)
                .intValue();
        cropX = (originalX - cropWidth) / 2;
        cropY = 0;
    }

    return new int[] { cropX, cropY, cropWidth, cropHeight };

}

From source file:org.projectforge.fibu.datev.EmployeeSalaryExportDao.java

/**
 * Exports the filtered list as table with almost all fields.
 *///from w w  w  .  jav a  2  s  .  c  o  m
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public byte[] export(final List<EmployeeSalaryDO> list) {
    log.info("Exporting employee salary list.");
    Validate.notEmpty(list);
    Collections.sort(list, new Comparator<EmployeeSalaryDO>() {
        public int compare(final EmployeeSalaryDO o1, final EmployeeSalaryDO o2) {
            return (o1.getEmployee().getUser().getFullname())
                    .compareTo(o2.getEmployee().getUser().getFullname());
        }
    });
    final EmployeeFilter filter = new EmployeeFilter();
    filter.setShowOnlyActiveEntries(true);
    filter.setDeleted(false);
    final List<EmployeeDO> employees = employeeDao.getList(filter);
    final List<EmployeeDO> missedEmployees = new ArrayList<EmployeeDO>();
    for (final EmployeeDO employee : employees) {
        boolean found = false;
        for (final EmployeeSalaryDO salary : list) {
            if (salary.getEmployeeId().equals(employee.getId()) == true) {
                found = true;
                break;
            }
        }
        if (found == false) {
            missedEmployees.add(employee);
        }
    }
    if (CollectionUtils.isNotEmpty(missedEmployees) == true) {
        Collections.sort(missedEmployees, new Comparator<EmployeeDO>() {
            public int compare(final EmployeeDO o1, final EmployeeDO o2) {
                return (o1.getUser().getFullname()).compareTo(o2.getUser().getFullname());
            }
        });
    }
    final ExportWorkbook xls = new ExportWorkbook();
    final ContentProvider contentProvider = new MyContentProvider(xls);
    // create a default Date format and currency column
    xls.setContentProvider(contentProvider);

    final EmployeeSalaryDO first = list.get(0);
    final int year = first.getYear();
    final int month = first.getMonth();
    final DayHolder buchungsdatum = new DayHolder();
    buchungsdatum.setDate(year, month, 1);
    final MonthHolder monthHolder = new MonthHolder(buchungsdatum.getDate());
    final BigDecimal numberOfWorkingDays = monthHolder.getNumberOfWorkingDays();
    buchungsdatum.setEndOfMonth();

    final String sheetTitle = DateHelper.formatMonth(year, month);
    final ExportSheet sheet = xls.addSheet(sheetTitle);
    sheet.createFreezePane(0, 1);

    final ExportSheet employeeSheet = xls.addSheet(PFUserContext.getLocalizedString("fibu.employee"));
    employeeSheet.setColumnWidth(0, XlsContentProvider.LENGTH_USER * 256);
    employeeSheet.setColumnWidth(1, 14 * 256);
    employeeSheet.setColumnWidth(2, 12 * 256);
    employeeSheet.setColumnWidth(3, 12 * 256);
    employeeSheet.setColumnWidth(4, 12 * 256);
    final ContentProvider provider = employeeSheet.getContentProvider();
    provider.putFormat("STUNDEN", "0.00;[Red]-0.00");
    final ExportRow employeeRow = employeeSheet.addRow();
    employeeRow.addCell(0, PFUserContext.getLocalizedString("fibu.employee"));
    employeeRow.addCell(1, PFUserContext.getLocalizedString("fibu.employee.wochenstunden"));
    employeeRow.addCell(2, PFUserContext.getLocalizedString("fibu.employee.sollstunden"));
    employeeRow.addCell(3, PFUserContext.getLocalizedString("fibu.employee.iststunden"));
    employeeRow.addCell(4, PFUserContext.getLocalizedString("fibu.common.difference"));

    // build all column names, title, widths from fixed and variable columns
    final int numCols = ExcelColumn.values().length;

    final String[] colNames = new String[numCols];
    final String[] colTitles = new String[numCols];
    final int[] colWidths = new int[numCols];

    int idx = 0;
    for (final ExcelColumn col : EnumSet.range(ExcelColumn.START, ExcelColumn.END)) {
        colNames[idx] = col.name();
        colTitles[idx] = PFUserContext.getLocalizedString(col.theTitle);
        colWidths[idx] = col.width;
        ++idx;
    }

    // column property names
    sheet.setPropertyNames(colNames);

    final ContentProvider sheetProvider = sheet.getContentProvider();
    sheetProvider.putFormat("STUNDEN", "0.00");
    sheetProvider.putFormat("BRUTTO_MIT_AG", "#,##0.00;[Red]-#,##0.00");
    sheetProvider.putFormat("KORREKTUR", "#,##0.00;[Red]-#,##0.00");
    sheetProvider.putFormat("SUMME", "#,##0.00;[Red]-#,##0.00");
    sheetProvider.putFormat("KOST1", "#");
    sheetProvider.putFormat("KOST2", "#");
    sheetProvider.putFormat("KONTO", "#");
    sheetProvider.putFormat("GEGENKONTO", "#");
    sheetProvider.putFormat("DATUM", "dd.MM.yyyy");
    // inform provider of column widths
    for (int ci = 0; ci < colWidths.length; ++ci) {
        sheetProvider.putColWidth(ci, colWidths[ci]);
    }

    final ExportRow headRow = sheet.addRow();
    int i = 0;
    for (final String title : colTitles) {
        headRow.addCell(i++, title);
    }

    for (final EmployeeSalaryDO salary : list) {
        final PropertyMapping mapping = new PropertyMapping();
        final PFUserDO user = userGroupCache.getUser(salary.getEmployee().getUserId());
        Validate.isTrue(year == salary.getYear());
        Validate.isTrue(month == salary.getMonth());
        final MonthlyEmployeeReport report = monthlyEmployeeReportDao.getReport(year, month, user);
        mapping.add(ExcelColumn.MITARBEITER, user.getFullname());
        final Kost1DO kost1 = salary.getEmployee().getKost1();
        final BigDecimal bruttoMitAGAnteil = salary.getBruttoMitAgAnteil();
        final BigDecimal netDuration = new BigDecimal(report.getTotalNetDuration());
        final Map<String, Kost2Row> rows = report.getKost2Rows();
        BigDecimal sum = BigDecimal.ZERO;
        int j = rows.size();
        for (final Kost2Row row : rows.values()) {
            final Kost2DO kost2 = row.getKost2();
            final MonthlyEmployeeReportEntry entry = report.getKost2Durations().get(kost2.getId());
            mapping.add(ExcelColumn.KOST1, kost1.getNummer());
            mapping.add(ExcelColumn.MITARBEITER, user.getFullname());
            mapping.add(ExcelColumn.KOST2, kost2.getNummer());
            final BigDecimal duration = new BigDecimal(entry.getMillis() / 1000); // Seconds
            // duration = duration.divide(new BigDecimal(60 * 60 * 24), 8, RoundingMode.HALF_UP); // Fraction of day (24 hours)
            // mapping.add(ExcelColumn.STUNDEN, duration);
            mapping.add(ExcelColumn.STUNDEN, duration.divide(new BigDecimal(3600), 2, RoundingMode.HALF_UP));
            mapping.add(ExcelColumn.BEZEICHNUNG, kost2.getToolTip());
            final BigDecimal betrag = CurrencyHelper.multiply(bruttoMitAGAnteil,
                    new BigDecimal(entry.getMillis()).divide(netDuration, 8, RoundingMode.HALF_UP));
            sum = sum.add(betrag);
            if (--j == 0) {
                final BigDecimal korrektur = bruttoMitAGAnteil.subtract(sum);
                mapping.add(ExcelColumn.BRUTTO_MIT_AG, betrag.add(korrektur));
                mapping.add(ExcelColumn.KORREKTUR, korrektur);
                if (NumberHelper.isEqual(sum.add(korrektur), bruttoMitAGAnteil) == true) {
                    mapping.add(ExcelColumn.SUMME, bruttoMitAGAnteil);
                } else {
                    mapping.add(ExcelColumn.SUMME, "*** " + sum + " != " + bruttoMitAGAnteil);
                }
            } else {
                mapping.add(ExcelColumn.BRUTTO_MIT_AG, betrag);
                mapping.add(ExcelColumn.KORREKTUR, "");
                mapping.add(ExcelColumn.SUMME, "");
            }
            mapping.add(ExcelColumn.DATUM, buchungsdatum.getCalendar()); // Last day of month
            mapping.add(ExcelColumn.KONTO, KONTO); // constant.
            mapping.add(ExcelColumn.GEGENKONTO, GEGENKONTO); // constant.
            sheet.addRow(mapping.getMapping(), 0);
        }
        addEmployeeRow(employeeSheet, salary.getEmployee(), numberOfWorkingDays, netDuration);
    }
    for (final EmployeeDO employee : missedEmployees) {
        final PFUserDO user = userGroupCache.getUser(employee.getUserId());
        final PropertyMapping mapping = new PropertyMapping();
        mapping.add(ExcelColumn.MITARBEITER, user.getFullname());
        mapping.add(ExcelColumn.SUMME, "***");
        mapping.add(ExcelColumn.BEZEICHNUNG, "*** FEHLT! ***");
        sheet.addRow(mapping.getMapping(), 0);
        final MonthlyEmployeeReport report = monthlyEmployeeReportDao.getReport(year, month, user);
        final BigDecimal netDuration = new BigDecimal(report.getTotalNetDuration());
        addEmployeeRow(employeeSheet, employee, numberOfWorkingDays, netDuration);
    }
    // sheet.setZoom(3, 4); // 75%

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        xls.write(baos);
    } catch (final IOException ex) {
        log.fatal("Exception encountered " + ex, ex);
        throw new RuntimeException(ex);
    }
    return baos.toByteArray();
}

From source file:org.projectforge.business.fibu.datev.EmployeeSalaryExportDao.java

/**
 * Exports the filtered list as table with almost all fields.
 *///from w ww  .  jav  a 2 s  .c  o  m
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public byte[] export(final List<EmployeeSalaryDO> list) {
    log.info("Exporting employee salary list.");
    Validate.notEmpty(list);
    Collections.sort(list, new Comparator<EmployeeSalaryDO>() {
        @Override
        public int compare(final EmployeeSalaryDO o1, final EmployeeSalaryDO o2) {
            return (o1.getEmployee().getUser().getFullname())
                    .compareTo(o2.getEmployee().getUser().getFullname());
        }
    });
    final EmployeeFilter filter = new EmployeeFilter();
    filter.setShowOnlyActiveEntries(true);
    filter.setDeleted(false);
    final List<EmployeeDO> employees = employeeDao.getList(filter);
    final List<EmployeeDO> missedEmployees = new ArrayList<EmployeeDO>();
    for (final EmployeeDO employee : employees) {
        boolean found = false;
        for (final EmployeeSalaryDO salary : list) {
            if (salary.getEmployeeId().equals(employee.getId()) == true) {
                found = true;
                break;
            }
        }
        if (found == false) {
            missedEmployees.add(employee);
        }
    }
    if (CollectionUtils.isNotEmpty(missedEmployees) == true) {
        Collections.sort(missedEmployees, new Comparator<EmployeeDO>() {
            @Override
            public int compare(final EmployeeDO o1, final EmployeeDO o2) {
                return (o1.getUser().getFullname()).compareTo(o2.getUser().getFullname());
            }
        });
    }
    final ExportWorkbook xls = new ExportWorkbook();
    final ContentProvider contentProvider = new MyContentProvider(xls);
    // create a default Date format and currency column
    xls.setContentProvider(contentProvider);

    final EmployeeSalaryDO first = list.get(0);
    final int year = first.getYear();
    final int month = first.getMonth();
    final DayHolder buchungsdatum = new DayHolder();
    buchungsdatum.setDate(year, month, 1);
    final MonthHolder monthHolder = new MonthHolder(buchungsdatum.getDate());
    final BigDecimal numberOfWorkingDays = monthHolder.getNumberOfWorkingDays();
    buchungsdatum.setEndOfMonth();

    final String sheetTitle = DateHelper.formatMonth(year, month);
    final ExportSheet sheet = xls.addSheet(sheetTitle);
    sheet.createFreezePane(0, 1);

    final ExportSheet employeeSheet = xls.addSheet(ThreadLocalUserContext.getLocalizedString("fibu.employee"));
    employeeSheet.setColumnWidth(0, MyXlsContentProvider.LENGTH_USER * 256);
    employeeSheet.setColumnWidth(1, 14 * 256);
    employeeSheet.setColumnWidth(2, 12 * 256);
    employeeSheet.setColumnWidth(3, 12 * 256);
    employeeSheet.setColumnWidth(4, 12 * 256);
    final ContentProvider provider = employeeSheet.getContentProvider();
    provider.putFormat("STUNDEN", "0.00;[Red]-0.00");
    final ExportRow employeeRow = employeeSheet.addRow();
    employeeRow.addCell(0, ThreadLocalUserContext.getLocalizedString("fibu.employee"));
    employeeRow.addCell(1, ThreadLocalUserContext.getLocalizedString("fibu.employee.wochenstunden"));
    employeeRow.addCell(2, ThreadLocalUserContext.getLocalizedString("fibu.employee.sollstunden"));
    employeeRow.addCell(3, ThreadLocalUserContext.getLocalizedString("fibu.employee.iststunden"));
    employeeRow.addCell(4, ThreadLocalUserContext.getLocalizedString("fibu.common.difference"));

    // build all column names, title, widths from fixed and variable columns
    final int numCols = ExcelColumn.values().length;

    final String[] colNames = new String[numCols];
    final String[] colTitles = new String[numCols];
    final int[] colWidths = new int[numCols];

    int idx = 0;
    for (final ExcelColumn col : EnumSet.range(ExcelColumn.START, ExcelColumn.END)) {
        colNames[idx] = col.name();
        colTitles[idx] = ThreadLocalUserContext.getLocalizedString(col.theTitle);
        colWidths[idx] = col.width;
        ++idx;
    }

    // column property names
    sheet.setPropertyNames(colNames);

    final ContentProvider sheetProvider = sheet.getContentProvider();
    sheetProvider.putFormat("STUNDEN", "0.00");
    sheetProvider.putFormat("BRUTTO_MIT_AG", "#,##0.00;[Red]-#,##0.00");
    sheetProvider.putFormat("KORREKTUR", "#,##0.00;[Red]-#,##0.00");
    sheetProvider.putFormat("SUMME", "#,##0.00;[Red]-#,##0.00");
    sheetProvider.putFormat("KOST1", "#");
    sheetProvider.putFormat("KOST2", "#");
    sheetProvider.putFormat("KONTO", "#");
    sheetProvider.putFormat("GEGENKONTO", "#");
    sheetProvider.putFormat("DATUM", "dd.MM.yyyy");
    // inform provider of column widths
    for (int ci = 0; ci < colWidths.length; ++ci) {
        sheetProvider.putColWidth(ci, colWidths[ci]);
    }

    final ExportRow headRow = sheet.addRow();
    int i = 0;
    for (final String title : colTitles) {
        headRow.addCell(i++, title);
    }

    for (final EmployeeSalaryDO salary : list) {
        final PropertyMapping mapping = new PropertyMapping();
        final PFUserDO user = getUserGroupCache().getUser(salary.getEmployee().getUserId());
        Validate.isTrue(year == salary.getYear());
        Validate.isTrue(month == salary.getMonth());
        final MonthlyEmployeeReport report = monthlyEmployeeReportDao.getReport(year, month, user);
        mapping.add(ExcelColumn.MITARBEITER, user.getFullname());
        final Kost1DO kost1 = salary.getEmployee().getKost1();
        final BigDecimal bruttoMitAGAnteil = salary.getBruttoMitAgAnteil();
        final BigDecimal netDuration = new BigDecimal(report.getTotalNetDuration());
        final Map<String, Kost2Row> rows = report.getKost2Rows();
        BigDecimal sum = BigDecimal.ZERO;
        int j = rows.size();
        for (final Kost2Row row : rows.values()) {
            final Kost2DO kost2 = row.getKost2();
            final MonthlyEmployeeReportEntry entry = report.getKost2Durations().get(kost2.getId());
            mapping.add(ExcelColumn.KOST1, kost1.getNummer());
            mapping.add(ExcelColumn.MITARBEITER, user.getFullname());
            mapping.add(ExcelColumn.KOST2, kost2.getNummer());
            final BigDecimal duration = new BigDecimal(entry.getMillis() / 1000); // Seconds
            // duration = duration.divide(new BigDecimal(60 * 60 * 24), 8, RoundingMode.HALF_UP); // Fraction of day (24 hours)
            // mapping.add(ExcelColumn.STUNDEN, duration);
            mapping.add(ExcelColumn.STUNDEN, duration.divide(new BigDecimal(3600), 2, RoundingMode.HALF_UP));
            mapping.add(ExcelColumn.BEZEICHNUNG, kost2.getToolTip());
            final BigDecimal betrag;
            if (NumberHelper.isNotZero(netDuration) == true) {
                betrag = CurrencyHelper.multiply(bruttoMitAGAnteil,
                        new BigDecimal(entry.getMillis()).divide(netDuration, 8, RoundingMode.HALF_UP));
            } else {
                betrag = BigDecimal.ZERO;
            }
            sum = sum.add(betrag);
            if (--j == 0) {
                final BigDecimal korrektur = bruttoMitAGAnteil.subtract(sum);
                mapping.add(ExcelColumn.BRUTTO_MIT_AG, betrag.add(korrektur));
                mapping.add(ExcelColumn.KORREKTUR, korrektur);
                if (NumberHelper.isEqual(sum.add(korrektur), bruttoMitAGAnteil) == true) {
                    mapping.add(ExcelColumn.SUMME, bruttoMitAGAnteil);
                } else {
                    mapping.add(ExcelColumn.SUMME, "*** " + sum + " != " + bruttoMitAGAnteil);
                }
            } else {
                mapping.add(ExcelColumn.BRUTTO_MIT_AG, betrag);
                mapping.add(ExcelColumn.KORREKTUR, "");
                mapping.add(ExcelColumn.SUMME, "");
            }
            mapping.add(ExcelColumn.DATUM, buchungsdatum.getCalendar()); // Last day of month
            mapping.add(ExcelColumn.KONTO, KONTO); // constant.
            mapping.add(ExcelColumn.GEGENKONTO, GEGENKONTO); // constant.
            sheet.addRow(mapping.getMapping(), 0);
        }
        addEmployeeRow(employeeSheet, salary.getEmployee(), numberOfWorkingDays, netDuration);
    }
    for (final EmployeeDO employee : missedEmployees) {
        final PFUserDO user = getUserGroupCache().getUser(employee.getUserId());
        final PropertyMapping mapping = new PropertyMapping();
        mapping.add(ExcelColumn.MITARBEITER, user.getFullname());
        mapping.add(ExcelColumn.SUMME, "***");
        mapping.add(ExcelColumn.BEZEICHNUNG, "*** FEHLT! ***");
        sheet.addRow(mapping.getMapping(), 0);
        final MonthlyEmployeeReport report = monthlyEmployeeReportDao.getReport(year, month, user);
        final BigDecimal netDuration = new BigDecimal(report.getTotalNetDuration());
        addEmployeeRow(employeeSheet, employee, numberOfWorkingDays, netDuration);
    }
    // sheet.setZoom(3, 4); // 75%

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        xls.write(baos);
    } catch (final IOException ex) {
        log.fatal("Exception encountered " + ex, ex);
        throw new RuntimeException(ex);
    }
    return baos.toByteArray();
}

From source file:strat.mining.stratum.proxy.worker.GetworkJobTemplate.java

/**
 * Compute the target based on the difficulty.
 * //from  w  w  w  .  j  a v a  2  s.  c  om
 * @param difficulty
 * @param isScrypt
 */
private void computeTarget(double difficulty, CryptoAlgorithm algo) {
    BigDecimal difficulty1 = new BigDecimal(0);
    switch (algo) {
    case Scrypt:
        difficulty1 = ScryptHashingUtils.DIFFICULTY_1_TARGET;
        break;
    case SHA256:
        difficulty1 = SHA256HashingUtils.DIFFICULTY_1_TARGET;
        break;
    default:
        throw new UnsupportedCryptoAlgorithmException(algo);
    }

    targetInteger = difficulty1.divide(BigDecimal.valueOf(difficulty), 0, RoundingMode.HALF_EVEN)
            .toBigInteger();
    byte[] bigEndianTargetBytes = targetInteger.toByteArray();

    // Build the target on 32 Bytes
    byte[] littleEndianTargetBytes = new byte[32];
    strat.mining.stratum.proxy.utils.ArrayUtils.copyInto(bigEndianTargetBytes, littleEndianTargetBytes,
            32 - bigEndianTargetBytes.length);
    // Then swap bytes from big-endian to little-endian
    littleEndianTargetBytes = strat.mining.stratum.proxy.utils.ArrayUtils.swapBytes(littleEndianTargetBytes, 4);
    // And reverse the order of 4-bytes words (big-endian to little-endian
    // 256-bits integer)
    littleEndianTargetBytes = strat.mining.stratum.proxy.utils.ArrayUtils.reverseWords(littleEndianTargetBytes,
            4);
    this.target = BaseEncoding.base16().encode(littleEndianTargetBytes);
}

From source file:edu.macalester.tagrelatedness.KendallsCorrelation.java

public BigDecimal get(BigDecimal n) {

    // Make sure n is a positive number

    if (n.compareTo(ZERO) <= 0) {
        throw new IllegalArgumentException();
    }/*w  w w  .  j av  a 2 s . c  o m*/

    BigDecimal initialGuess = getInitialApproximation(n);
    trace("Initial guess " + initialGuess.toString());
    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);
        trace("Next guess " + guess.toString());
        error = n.subtract(guess.multiply(guess));
        if (++iterations >= maxIterations) {
            more = false;
        } else if (lastGuess.equals(guess)) {
            more = error.abs().compareTo(ONE) >= 0;
        }
    }
    return guess;

}

From source file:org.talend.dataprep.transformation.actions.math.NumericOperations.java

protected String compute(final String stringOperandOne, final String operator, final String stringOperandTwo) {
    if (!NumericHelper.isBigDecimal(stringOperandOne) || !NumericHelper.isBigDecimal(stringOperandTwo)) {
        return StringUtils.EMPTY;
    }// w  w  w . j a  v a2  s.c om

    try {
        final BigDecimal operandOne = BigDecimalParser.toBigDecimal(stringOperandOne);
        final BigDecimal operandTwo = BigDecimalParser.toBigDecimal(stringOperandTwo);

        BigDecimal toReturn;

        final int scale = 2;
        final RoundingMode rm = HALF_UP;

        switch (operator) {
        case PLUS:
            toReturn = operandOne.add(operandTwo);
            break;
        case MULTIPLY:
            toReturn = operandOne.multiply(operandTwo);
            break;
        case MINUS:
            toReturn = operandOne.subtract(operandTwo);
            break;
        case DIVIDE:
            toReturn = operandOne.divide(operandTwo, scale, rm);
            break;
        default:
            return "";
        }

        // Format result:
        return toReturn.setScale(scale, rm).stripTrailingZeros().toPlainString();
    } catch (ArithmeticException | NullPointerException e) {
        return StringUtils.EMPTY;
    }
}

From source file:org.openvpms.archetype.rules.product.ProductPriceRules.java

/**
 * Calculates the maximum discount that can be applied for a given markup.
 * <p/>/* w ww  . j  a v  a2 s .co m*/
 * Uses the equation:
 * <code>(markup / (100 + markup)) * 100</code>
 *
 * @param markup the markup expressed as a percentage
 * @return the discount as a percentage rounded down
 */
public BigDecimal calcMaxDiscount(BigDecimal markup) {
    BigDecimal discount = DEFAULT_MAX_DISCOUNT;
    if (markup.compareTo(BigDecimal.ZERO) > 0) {
        discount = markup.divide(ONE_HUNDRED.add(markup), 3, RoundingMode.HALF_DOWN).multiply(ONE_HUNDRED);
    }
    return discount;
}

From source file:module.siadap.domain.SiadapEvaluationUniverse.java

private BigDecimal getEvaluationScoring(List<? extends SiadapEvaluationItem> evaluations) {

    if (!isEvaluationScoringComplete(evaluations)) {
        return BigDecimal.ZERO;
    }// w  w w  .  j ava2s  .  co  m

    BigDecimal result = new BigDecimal(0);
    for (SiadapEvaluationItem evaluation : evaluations) {
        IScoring itemEvaluation = evaluation.getItemEvaluation();
        if (itemEvaluation == null) {
            throw new SiadapException("error.siadapEvaluation.mustFillAllItems");
        }
        result = result.add(itemEvaluation.getPoints());
    }

    if (evaluations.size() == 0) {
        return BigDecimal.ZERO;
    }
    return result.divide(new BigDecimal(evaluations.size()), PRECISION, ROUND_MODE);
}