Example usage for java.lang Math floor

List of usage examples for java.lang Math floor

Introduction

In this page you can find the example usage for java.lang Math floor.

Prototype

public static double floor(double a) 

Source Link

Document

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

Usage

From source file:marytts.util.string.StringUtils.java

public static String[] indexedNameGenerator(String preName, int numFiles, int startIndex, String postName,
        String extension, int numDigits) {
    String[] fileList = null;//from  w w w.j  av  a  2  s . c  o m

    if (numFiles > 0) {
        if (startIndex < 0)
            startIndex = 0;

        int tmpDigits = (int) Math.floor(Math.log10(startIndex + numFiles - 1));
        if (tmpDigits > numDigits)
            numDigits = tmpDigits;

        fileList = new String[numFiles];

        String strNum;

        for (int i = startIndex; i < startIndex + numFiles; i++) {
            strNum = String.valueOf(i);

            //Add sufficient 0s in the beginning
            while (strNum.length() < numDigits)
                strNum = "0" + strNum;
            //

            fileList[i - startIndex] = preName + strNum + postName + extension;
        }
    }

    return fileList;
}

From source file:edu.umn.cs.spatialHadoop.nasa.SpatioAggregateQueries.java

/**
 * Performs a spatio-temporal aggregate query on an indexed directory
 * @param inFile//from w ww .  j av a 2 s.  c  o  m
 * @param params
 * @throws ParseException 
 * @throws IOException 
 * @throws InterruptedException 
 */
public static long selectionQuery(Path inFile, final ResultCollector<NASAPoint> output, OperationsParams params)
        throws ParseException, IOException, InterruptedException {
    // 1- Find matching temporal partitions
    final FileSystem fs = inFile.getFileSystem(params);
    Vector<Path> matchingPartitions = selectTemporalPartitions(inFile, params);

    // 2- Find the matching tile and the position in that tile
    final Point queryPoint = (Point) params.getShape("point");
    final double userQueryLon = queryPoint.x;
    final double userQueryLat = queryPoint.y;
    // Convert query point from lat/lng space to Sinusoidal space
    double cosPhiRad = Math.cos(queryPoint.y * Math.PI / 180);
    double projectedX = queryPoint.x * cosPhiRad;
    queryPoint.x = (projectedX + 180.0) / 10.0;
    queryPoint.y = (90.0 - queryPoint.y) / 10.0;
    final int h = (int) Math.floor(queryPoint.x);
    final int v = (int) Math.floor(queryPoint.y);
    final String tileID = String.format("h%02dv%02d", h, v);
    PathFilter rangeFilter = new PathFilter() {
        @Override
        public boolean accept(Path p) {
            return p.getName().indexOf(tileID) >= 0;
        }
    };

    final Vector<Path> allMatchingFiles = new Vector<Path>();

    for (Path matchingPartition : matchingPartitions) {
        // Select all matching files
        FileStatus[] matchingFiles = fs.listStatus(matchingPartition, rangeFilter);
        for (FileStatus matchingFile : matchingFiles) {
            allMatchingFiles.add(matchingFile.getPath());
        }
    }

    // All matching files are supposed to have the same resolution
    final int resolution = AggregateQuadTree.getResolution(fs, allMatchingFiles.get(0));

    final java.awt.Point queryInMatchingTile = new java.awt.Point();
    queryInMatchingTile.x = (int) Math.floor((queryPoint.x - h) * resolution);
    queryInMatchingTile.y = (int) Math.floor((queryPoint.y - v) * resolution);

    // 3- Query all matching files in parallel
    List<Long> threadsResults = Parallel.forEach(allMatchingFiles.size(), new RunnableRange<Long>() {
        @Override
        public Long run(int i1, int i2) {
            ResultCollector<AggregateQuadTree.PointValue> internalOutput = output == null ? null
                    : new ResultCollector<AggregateQuadTree.PointValue>() {
                        NASAPoint middleValue = new NASAPoint(userQueryLon, userQueryLat, 0, 0);

                        @Override
                        public void collect(AggregateQuadTree.PointValue value) {
                            middleValue.value = value.value;
                            middleValue.timestamp = value.timestamp;
                            output.collect(middleValue);
                        }
                    };

            long numOfResults = 0;
            for (int i_file = i1; i_file < i2; i_file++) {
                try {
                    Path matchingFile = allMatchingFiles.get(i_file);
                    java.awt.Rectangle query = new java.awt.Rectangle(queryInMatchingTile.x,
                            queryInMatchingTile.y, 1, 1);
                    AggregateQuadTree.selectionQuery(fs, matchingFile, query, internalOutput);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return numOfResults;
        }
    });
    long totalResults = 0;
    for (long result : threadsResults) {
        totalResults += result;
    }
    return totalResults;
}

From source file:edu.byu.nlp.data.app.AnnotationStream2Annotators.java

public static int[] clusterAnnotatorParameters(double[][][] annotatorParameters,
        ClusteringMethod clusteringMethod, int k, int maxIterations, double smooth, RandomGenerator rnd) {
    Preconditions.checkNotNull(annotatorParameters);
    Preconditions.checkArgument(annotatorParameters.length > 0);
    int numAnnotators = annotatorParameters.length;

    // put each annotator in a singleton cluster
    List<Annotator> annotators = Lists.newArrayList();
    for (int i = 0; i < numAnnotators; i++) {
        annotators.add(new Annotator(annotatorParameters[i], i, i));
    }// w ww  .  ja  va2  s  .  c  om

    // precompute potenially useful quantities
    double uniformClusterSize = (double) numAnnotators / k;

    // transformed confusion matrices
    switch (clusteringMethod) {
    case NONE:
        break;
    case RANDOM:
        // shuffle, then assign in equal blocks 
        Collections.shuffle(annotators, new RandomAdaptor(rnd));
        for (int c = 0; c < k; c++) {
            int start = (int) Math.floor(c * uniformClusterSize);
            int end = (int) Math.floor(c * uniformClusterSize + uniformClusterSize);
            for (int a = start; a < end; a++) {
                annotators.get(a).clusterAssignment = c;
            }
        }
        break;
    case ACCURACY:
        logger.debug("sorting annotators by accuracy");
        Collections.sort(annotators); // re-order annotators so that more accurate ones appear first
        for (int i = 0; i < annotatorParameters.length; i++) {
            logger.debug("annotator #" + i + " accuracy=" + accuracyOf(annotatorParameters[i]));
        }
        // now divide annotators into equal chunks--like accuracies will cluster together
        for (int c = 0; c < k; c++) {
            int start = (int) Math.floor(c * uniformClusterSize);
            int end = (int) Math.floor(c * uniformClusterSize + uniformClusterSize);
            for (int a = start; a < end; a++) {
                annotators.get(a).clusterAssignment = c;
            }
        }
        break;
    case KMEANS:
        assignKMeansClusters(annotators, k, maxIterations, rnd);
        break;
    default:
        throw new IllegalArgumentException("unknown aggregation method=" + clusteringMethod);
    }

    // return the mapping vector
    int[] clusterAssignments = new int[numAnnotators];
    for (int a = 0; a < numAnnotators; a++) {
        Annotator annotator = annotators.get(a);
        clusterAssignments[annotator.index] = annotator.clusterAssignment;
    }

    return clusterAssignments;
}

From source file:edu.stanford.cfuller.imageanalysistools.clustering.ObjectClustering.java

/**
 * Sets up a set of ClusterObjects and a set of Clusters from an Image mask with each object labeled with a unique greylevel.
 *
 * @param im                The Image mask with each cluster object labeled with a unique greylevel.  These must start at 1 and be consecutive.
 * @param clusterObjects    A Vector of ClusterObjects that will contain the initialized ClusterObjects on return; this may be empty, and any contents will be erased.
 * @param clusters          A Vector of Clusters that will contain the initialized Clusters on return; this may be empty, and any contents will be erased.
 * @param k                 The number of Clusters to generate.
 * @return                  The number of ClusterObjects in the Image.
 *///from  w w w.  j a  v  a  2s  . c o m
public static int initializeObjectsAndClustersFromImage(Image im, Vector<ClusterObject> clusterObjects,
        Vector<Cluster> clusters, int k) {

    int n = 0;

    clusters.clear();

    for (int j = 0; j < k; j++) {

        clusters.add(new Cluster());
        clusters.get(j).setID(j + 1);

    }

    Histogram h = new Histogram(im);

    n = h.getMaxValue();

    clusterObjects.clear();

    for (int j = 0; j < n; j++) {

        clusterObjects.add(new ClusterObject());

        clusterObjects.get(j).setCentroidComponents(0, 0, 0);

        clusterObjects.get(j).setnPixels(0);

    }

    for (ImageCoordinate i : im) {

        if (im.getValue(i) > 0) {

            ClusterObject current = clusterObjects.get((int) im.getValue(i) - 1);

            current.incrementnPixels();

            current.setCentroid(current.getCentroid().add(new Vector3D(i.get(ImageCoordinate.X),
                    i.get(ImageCoordinate.Y), i.get(ImageCoordinate.Z))));

        }

    }

    for (int j = 0; j < n; j++) {
        ClusterObject current = clusterObjects.get(j);
        current.setCentroid(current.getCentroid().scalarMultiply(1.0 / current.getnPixels()));
    }

    //initialize clusters using kmeans++ strategy

    double[] probs = new double[n];
    double[] cumulativeProbs = new double[n];

    java.util.Arrays.fill(probs, 0);
    java.util.Arrays.fill(cumulativeProbs, 0);

    //choose the initial cluster

    int initialClusterObject = (int) Math.floor(n * RandomGenerator.rand());

    clusters.get(0).setCentroid(clusterObjects.get(initialClusterObject).getCentroid());

    clusters.get(0).getObjectSet().add(clusterObjects.get(initialClusterObject));

    for (int j = 0; j < n; j++) {

        clusterObjects.get(j).setCurrentCluster(clusters.get(0));
    }

    //assign the remainder of the clusters

    for (int j = 1; j < k; j++) {

        double probSum = 0;

        for (int m = 0; m < n; m++) {
            double minDist = Double.MAX_VALUE;

            Cluster bestCluster = null;

            for (int p = 0; p < j; p++) {

                double tempDist = clusterObjects.get(m).distanceTo(clusters.get(p));

                if (tempDist < minDist) {
                    minDist = tempDist;

                    bestCluster = clusters.get(p);
                }

            }

            probs[m] = minDist;
            probSum += minDist;

            clusterObjects.get(m).setCurrentCluster(bestCluster);
        }

        for (int m = 0; m < n; m++) {
            probs[m] = probs[m] / probSum;
            if (m == 0) {
                cumulativeProbs[m] = probs[m];
            } else {
                cumulativeProbs[m] = cumulativeProbs[m - 1] + probs[m];
            }
        }
        double randNum = RandomGenerator.rand();
        int nextCenter = 0;

        for (int m = 0; m < n; m++) {
            if (randNum < cumulativeProbs[m]) {
                nextCenter = m;
                break;
            }
        }

        clusters.get(j).setCentroid(clusterObjects.get(nextCenter).getCentroid());

    }

    for (int m = 0; m < n; m++) {

        double minDist = Double.MAX_VALUE;

        Cluster bestCluster = null;

        for (int p = 0; p < k; p++) {

            double tempDist = clusterObjects.get(m).distanceTo(clusters.get(p));

            if (tempDist < minDist) {

                minDist = tempDist;
                bestCluster = clusters.get(p);
            }
        }

        clusterObjects.get(m).setCurrentCluster(bestCluster);
        bestCluster.getObjectSet().add(clusterObjects.get(m));

    }

    return n;
}

From source file:beast.math.distributions.GammaDistribution.java

public static double nextGamma(double shape, double scale, boolean slowCode) {

    double sample = 0.0;

    if (shape < 0.00001) {

        if (shape < 0) {
            System.out.println("Negative shape parameter");
            throw new IllegalArgumentException("Negative shape parameter");
        }//from  w w  w.  j  a  v  a2 s  .c om

        /*
        * special case: shape==0.0 is an improper distribution; but
        * sampling works if very small values are ignored (v. large ones
        * don't happen) This is useful e.g. for sampling from the truncated
        * Gamma(0,x)-distribution.
        */

        double minimum = 1.0e-20;
        double maximum = 50;
        double normalizingConstant = Math.log(maximum) - Math.log(minimum);
        // Draw from 1/x (with boundaries), and shape by exp(-x)
        do {
            sample = Math.exp(Math.log(minimum) + normalizingConstant * MathUtils.nextDouble());
        } while (Math.exp(-sample) < MathUtils.nextDouble());
        // This distribution is actually scale-free, so multiplying by
        // 'scale' is not necessary
        return sample;
    }

    if (slowCode && Math.floor(shape) == shape && shape > 4.0) {
        for (int i = 0; i < shape; i++)
            sample += -Math.log(MathUtils.nextDouble());
        return sample * scale;
    } else {

        // Fast special cases
        if (shape == 1.0) {
            return -Math.log(MathUtils.nextDouble()) * scale;
        }
        if (shape == 2.0) {
            return -Math.log(MathUtils.nextDouble() * MathUtils.nextDouble()) * scale;
        }
        if (shape == 3.0) {
            return -Math.log(MathUtils.nextDouble() * MathUtils.nextDouble() * MathUtils.nextDouble()) * scale;
        }
        if (shape == 4.0) {
            return -Math.log(MathUtils.nextDouble() * MathUtils.nextDouble() * MathUtils.nextDouble()
                    * MathUtils.nextDouble()) * scale;
        }
    }

    // general case
    do {
        try {
            sample = quantile(MathUtils.nextDouble(), shape, scale);
        } catch (IllegalArgumentException e) {
            // random doubles do go outside the permissible range 0.000002 <
            // q < 0.999998
            sample = 0.0;
        }
    } while (sample == 0.0);
    return sample;
}

From source file:com.ssbusy.controller.checkout.CheckoutController.java

/**
 * TODO show cart?checkout// w  ww . j av  a  2s .  co  m
 */
@RequestMapping("/checkout")
public String checkout(Model model) {
    Region region = null;
    MyCustomer myCustomer = (MyCustomer) CustomerState.getCustomer();
    region = myCustomer.getRegion();
    if (CartState.getCart() != null) {
        Money total = CartState.getCart().getTotal();
        if (total != null && Math.floor(total.doubleValue()) != total.doubleValue()) {
            List<Inventory> invs = inventoryService.findProductsByPriceAndCurrency(total.getAmount(),
                    CartState.getCart().getCurrency(), region.getFulfillmentLocations(), 0, 12);
            if (couzheng_show_quantity < invs.size()) {
                invs = invs.subList(0, couzheng_show_quantity);
            }
            model.addAttribute("inventories", invs);
        }
    }
    // ??
    List<Offer> offers = offerService.findAllOffers();
    for (Iterator<Offer> iterator = offers.iterator(); iterator.hasNext();) {
        Offer offer = null;
        offer = iterator.next();

        if (!((Status) offer).isActive()) {
            iterator.remove();
        }
    }
    if (offers.iterator() != null) {
        Iterator<Offer> iterator = offers.iterator();
        while (iterator.hasNext()) {
            // To do
            Offer offer = iterator.next();
            if (offer.getOfferMatchRules().get(OfferRuleType.CUSTOMER.getType()) != null) {

                String maprule = offer.getOfferMatchRules().get(OfferRuleType.CUSTOMER.getType())
                        .getMatchRule();
                HashMap<String, Object> vars = new HashMap<String, Object>();
                vars.put("customer", myCustomer);
                Boolean expressionOutcome = executeExpression(maprule, vars);
                if (expressionOutcome == null || !expressionOutcome) {
                    iterator.remove();
                }
            }
        }

    }

    model.addAttribute("offers", offers);
    List<MyOfferCode> myOfferCodes = offerService.listOfferCodeByOwner(CustomerState.getCustomer().getId());
    model.addAttribute("offercodes", myOfferCodes);
    return getCheckoutView();
}

From source file:com.primeleaf.krystal.web.view.console.CheckInDocumentView.java

@SuppressWarnings("unchecked")
private void printCheckInDocumentForm() throws Exception {
    printBreadCrumbs();/*from  w  ww .j  a v  a 2 s .co m*/
    Document document = (Document) request.getAttribute("DOCUMENT");
    DocumentClass documentClass = (DocumentClass) request.getAttribute("DOCUMENTCLASS");
    LinkedHashMap<String, String> documentIndexes = (LinkedHashMap<String, String>) request
            .getAttribute("DOCUMENTINDEXES");

    if (request.getAttribute(HTTPConstants.REQUEST_ERROR) != null) {
        printError((String) request.getAttribute(HTTPConstants.REQUEST_ERROR));
    }
    if (request.getAttribute(HTTPConstants.REQUEST_MESSAGE) != null) {
        printSuccess((String) request.getAttribute(HTTPConstants.REQUEST_MESSAGE));
    }
    if (document != null) {
        try {
            out.println("<div class=\"panel panel-default\">");
            out.println("<div class=\"panel-heading\"><h4><i class=\"fa fa-lg fa-arrow-right\"></i> Check In - "
                    + documentClass.getClassName() + "</h4></div>");
            out.println("<div class=\"panel-body\">");

            out.println(
                    "<form action=\"/console/checkindocument\" method=\"post\" id=\"frmCheckInDocument\" class=\"form-horizontal\" enctype=\"multipart/form-data\" accept-charset=\"utf-8\">");
            out.println("<div class=\"form-group\">");
            out.println("<div class=\"col-sm-offset-3 col-sm-9\">");
            out.println("<p>Fields marked with <span style='color:red'>*</span> are mandatory</p>");
            out.println("</div>");
            out.println("</div>");

            out.println("<div class=\"form-group\">");
            out.println(
                    "<label for=\"fileDocument\" class=\"col-sm-3 control-label\">Select Document <span style='color:red'>*</span></label>");
            out.println("<div class=\"col-sm-9\">");
            out.println(
                    "<input type=\"file\" name=\"fileDocument\" class=\"required checkExtension\" title=\"Select document of type "
                            + document.getExtension() + " to check-in\">");
            out.println("</div>");
            out.println("</div>");

            for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) {
                String required = "";
                out.println("<div class=\"form-group\">");
                out.println("<label for=\"" + indexDefinition.getIndexColumnName()
                        + "\" class=\"col-sm-3 control-label\"> "
                        + StringEscapeUtils.escapeHtml4(indexDefinition.getIndexDisplayName()));
                if (indexDefinition.isMandatory()) {
                    required = "required";
                    out.println(" <span style='color:red'>*</span>");
                }
                out.println("</label>");

                String value = documentIndexes.get(indexDefinition.getIndexDisplayName());
                value = StringEscapeUtils.escapeHtml4(value);

                if (indexDefinition.getIndexType().equals(IndexDefinition.INDEXTYPE_DATE)) {
                    out.println("<div class=\"col-sm-2\">");
                    out.println("<div class=\"input-group\">");
                    out.println("<input type=\"text\" class=\"shortdate isdate form-control " + required
                            + "\" size=\"" + indexDefinition.getIndexMaxLength() + "\" name=\""
                            + indexDefinition.getIndexColumnName() + "\" id=\""
                            + indexDefinition.getIndexColumnName() + "\" value=\"" + value + "\" maxlength=\""
                            + indexDefinition.getIndexMaxLength() + "\"  cid=\"" + documentClass.getClassId()
                            + "\">");
                    out.println("<span class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i></span>");
                    out.println("</div>");
                    out.println("</div>");
                } else if (indexDefinition.getIndexType().equals(IndexDefinition.INDEXTYPE_NUMBER)) {
                    out.println("<div class=\"col-sm-9\">");
                    out.println("<input type=\"text\" class=\"number  form-control " + required
                            + " autocomplete\"  size=\"" + indexDefinition.getIndexMaxLength() + "\"  id=\""
                            + indexDefinition.getIndexColumnName() + "\" name=\""
                            + indexDefinition.getIndexColumnName() + "\" value=\"" + value + "\" maxlength=\""
                            + indexDefinition.getIndexMaxLength() + "\"   cid=\"" + documentClass.getClassId()
                            + "\">");
                    out.println("</div>");
                } else {
                    out.println("<div class=\"col-sm-9\">");
                    out.println("<input type=\"text\"  class=\"autocomplete form-control " + required
                            + " \" id=\"" + indexDefinition.getIndexColumnName() + "\"  name=\""
                            + indexDefinition.getIndexColumnName() + "\" value=\"" + value + "\"maxlength=\""
                            + indexDefinition.getIndexMaxLength() + "\"  cid=\"" + documentClass.getClassId()
                            + "\">");
                    out.println("</div>");
                }
                out.println("</div>");
            }

            double rev = Double.parseDouble(document.getRevisionId());
            DecimalFormat onePlace = new DecimalFormat("0.0");
            // For minor revision id
            double minorRevisionId = rev + 0.1;
            // For major revision id
            rev = Math.floor(rev);
            double majorRevisionId = rev + 1.0;

            // revision number field
            out.println("<div class=\"form-group\">");
            out.println("<label for=\"version\" class=\"col-sm-3 control-label\">Version</label>");
            out.println("<div class=\"btn-group col-sm-9\" data-toggle=\"buttons\">");
            out.println("<label class=\"btn  btn-sm btn-default active\">");
            out.println("<input type=\"radio\" id=\"version1\" name=\"version\" value=\"minor\" checked>Minor ("
                    + onePlace.format(minorRevisionId) + ")");
            out.println("</label>");
            out.println("<label class=\"btn  btn-sm btn-default\">");
            out.println("<input type=\"radio\" id=\"version2\" name=\"version\"  value=\"major\">Major ("
                    + onePlace.format(majorRevisionId) + ")");
            out.println("</label>");
            out.println("</div>");
            out.println("</div>");

            out.println("<div class=\"form-group\">");
            out.println("<label for=\"txtNote\" class=\"col-sm-3 control-label\">Note / Comment </label>");
            out.println("<div class=\"col-sm-9\">");
            out.println(
                    "<textarea rows=\"3\" name=\"txtNote\" id=\"txtNote\" class=\"form-control\"></textarea>");
            out.println("</div>");
            out.println("</div>");
            out.println("<hr/>");
            out.println("<div class=\"form-group\">");
            out.println("<div class=\"col-sm-offset-3 col-sm-9\">");
            out.println(
                    "<input type=\"hidden\" name=\"documentid\" value=\"" + document.getDocumentId() + "\">");
            out.println("<input type=\"hidden\" name=\"fileExtension\" id=\"fileExtension\" value=\""
                    + document.getExtension().toUpperCase() + "\">");
            out.println(
                    "<input type=\"submit\"  name=\"btnSubmit\"  value=\"Check In\" class=\"btn btn-sm btn-default\">");
            out.println("</div>");
            out.println("</div>");
            out.println("</form>");

            out.println("</div>"); //panel-body
            out.println("</div>"); //panel
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:it.unibo.alchemist.modelchecker.AlchemistASMC.java

private static int computeMinimum(final double interval, final double confidence) {
    final UnivariateFunction f = new UnivariateFunction() {
        @Override// w w  w . j  av  a2 s.  co m
        public double value(final double n) {
            double t;
            if (Math.ceil(n) == FastMath.floor(n)) {
                t = new TDistribution((int) n).inverseCumulativeProbability(1 - confidence / 2);
            } else {
                double t1 = new TDistribution((int) FastMath.ceil(n))
                        .inverseCumulativeProbability((1 - confidence / 2)) * (n - Math.floor(n));
                double t2 = new TDistribution((int) FastMath.floor(n))
                        .inverseCumulativeProbability((1 - confidence / 2)) * (Math.ceil(n) - n);
                t = t1 + t2;
            }
            double value = 2 * t / n;
            return value - interval;
        }
    };
    final BisectionSolver bs = new BisectionSolver();
    return (int) Math.ceil(bs.solve(Integer.MAX_VALUE, f, 1, Integer.MAX_VALUE));
}

From source file:com.diozero.devices.ADXL345.java

/**
  * Set the tap threshold in g/*from  w  ww . j av  a 2s.co  m*/
  * @param tapThreshold The threshold value in g for tap interrupts
  */
public void setTapThreshold(float tapThreshold) {
    if (tapThreshold < 0 || tapThreshold > THRESH_TAP_RANGE) {
        throw new IllegalArgumentException(
                "Illegal tap threshold value (" + tapThreshold + "), must be 0.." + THRESH_TAP_RANGE);
    }
    device.writeByte(THRESH_TAP, (byte) (Math.floor(tapThreshold / THRESH_TAP_LSB)));
}

From source file:org.jamwiki.utils.ImageUtil.java

/**
 *
 *//*from   www  . j  av  a 2 s  . com*/
private static void setScaledDimensions(BufferedImage bufferedImage, WikiImage wikiImage, int maxDimension) {
    int width = bufferedImage.getWidth();
    int height = bufferedImage.getHeight();
    if (width >= height) {
        height = (int) Math.floor(((double) maxDimension / (double) width) * (double) height);
        width = maxDimension;
    } else {
        width = (int) Math.floor(((double) maxDimension / (double) height) * (double) width);
        height = maxDimension;
    }
    wikiImage.setWidth(width);
    wikiImage.setHeight(height);
}