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:es.udc.gii.common.eaf.benchmark.real_param.cec2005.CEC2005ObjectiveFunction.java

/**
 * Rounds a value to a integer value. The rouding is performed as defined by
 * the CEC 2005 technical report.//from   w  ww  . ja v  a  2 s.c om
 * @param x
 * @return {@code x} rounded to an integer value.
 */
public final double round(double x) {
    return Math.floor(x + 0.5);
}

From source file:it.unimi.dsi.sux4j.mph.VLPaCoTrieDistributorMonotoneMinimalPerfectHashFunction.java

/** Creates a new PaCo-trie-based monotone minimal perfect hash function using the given
 * elements and transformation strategy. 
 * //from  w w w.  j  a  va2s. co m
 * @param elements the elements among which the trie must be able to rank.
 * @param transform a transformation strategy that must turn the elements in <code>elements</code> into a list of
 * distinct, prefix-free, lexicographically increasing (in iteration order) bit vectors.
 */
public VLPaCoTrieDistributorMonotoneMinimalPerfectHashFunction(final Iterable<? extends T> elements,
        final TransformationStrategy<? super T> transform) throws IOException {

    this.transform = transform;
    defRetValue = -1; // For the very few cases in which we can decide

    long maxLength = 0;
    long totalLength = 0;
    BitVector bv;
    final RandomGenerator random = new XorShift1024StarRandomGenerator();
    ProgressLogger pl = new ProgressLogger(LOGGER);
    pl.displayLocalSpeed = true;
    pl.displayFreeMemory = true;
    pl.itemsName = "keys";

    pl.start("Creating chunked hash store...");
    final ChunkedHashStore<BitVector> chunkedHashStore = new ChunkedHashStore<BitVector>(
            TransformationStrategies.identity());
    chunkedHashStore.reset(random.nextLong());
    for (T s : elements) {
        bv = transform.toBitVector(s);
        chunkedHashStore.add(bv);
        maxLength = Math.max(maxLength, bv.length());
        totalLength += bv.length();
        pl.lightUpdate();
    }

    pl.done();

    size = chunkedHashStore.size();

    if (size == 0) {
        bucketSize = log2BucketSize = 0;
        distributor = null;
        offset = null;
        chunkedHashStore.close();
        return;
    }

    final long averageLength = (totalLength + size - 1) / size;

    int t = Fast.mostSignificantBit(
            (int) Math.floor(averageLength - Math.log(size) - Math.log(averageLength - Math.log(size)) - 1));
    final int firstbucketSize = 1 << t;
    LOGGER.debug("First bucket size estimate: " + firstbucketSize);

    final Iterable<BitVector> bitVectors = TransformationStrategies.wrap(elements, transform);

    VLPaCoTrieDistributor<BitVector> firstDistributor = new VLPaCoTrieDistributor<BitVector>(bitVectors, size,
            firstbucketSize, TransformationStrategies.identity());

    if (firstDistributor.numBits() == 0 || firstbucketSize >= size)
        log2BucketSize = t;
    else {
        // Reassign bucket size based on empirical estimation
        log2BucketSize = t
                - Fast.mostSignificantBit((int) Math.ceil(size / (firstDistributor.numBits() * Math.log(2))));
    }

    bucketSize = 1 << log2BucketSize;
    LOGGER.debug("Second bucket size estimate: " + bucketSize);

    if (firstbucketSize == bucketSize)
        distributor = firstDistributor;
    else {
        firstDistributor = null;
        distributor = new VLPaCoTrieDistributor<BitVector>(bitVectors, size, bucketSize,
                TransformationStrategies.identity());
    }

    LOGGER.info("Bucket size: " + bucketSize);

    final SparseRank sparseRank;
    if (size > 2 * bucketSize) {
        sparseRank = new SparseRank(distributor.offset.getLong(distributor.offset.size64() - 1) + 1,
                distributor.offset.size64(), distributor.offset.iterator());
        if (ASSERTS) {
            long i = 0;
            for (BitVector b : bitVectors) {
                final long d = distributor.getLong(b);
                assert sparseRank.rank(i) == d : "At " + i + ": " + sparseRank.rank(i) + " != " + d;
                i++;
            }
        }

        select = sparseRank.getSelect();
    } else {
        sparseRank = null;
        select = null;
    }

    if (size > 0) {
        offset = new GOV3Function.Builder<BitVector>().keys(bitVectors)
                .transform(TransformationStrategies.identity()).store(chunkedHashStore)
                .values(new AbstractLongBigList() {
                    public long getLong(long index) {
                        final long rank = sparseRank == null ? 0 : sparseRank.rank(index);
                        if (ASSERTS) {
                            assert rank == 0
                                    || distributor.offset.getLong(rank - 1) <= index : distributor.offset
                                            .getLong(rank - 1) + " >= " + index + "(rank=" + rank + ")";
                            assert rank == 0 && index < bucketSize * 2 || rank > 0
                                    && index - distributor.offset.getLong(rank - 1) < bucketSize * 2;
                        }
                        return rank == 0 ? index : index - distributor.offset.getLong(rank - 1);
                    }

                    public long size64() {
                        return size;
                    }
                }, log2BucketSize + 1).indirect().build();

    } else
        offset = null;

    chunkedHashStore.close();

    LOGGER.debug("Forecast distributor bit cost: "
            + (size / bucketSize) * (maxLength + log2BucketSize - Math.log(size)));
    LOGGER.debug("Actual distributor bit cost: " + distributor.numBits());
    LOGGER.debug("Forecast bit cost per element: " + (GOV3Function.C + Fast.log2(Math.E)
            - Fast.log2(Fast.log2(Math.E)) + Fast.log2(maxLength - Fast.log2(size))));
    LOGGER.info("Actual bit cost per element: " + (double) numBits() / size);
}

From source file:de.romankreisel.faktotum.beans.BundesbruderBean.java

public void rotateProfilePictureClockwise(BundesbruderEntity bundesbruder, double angle) throws IOException {
    BufferedImage image = this.getImageFromByteArray(bundesbruder.getPictureOriginal());
    double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
    int w = image.getWidth(), h = image.getHeight();
    int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h * cos + w * sin);
    GraphicsConfiguration gc = image.createGraphics().getDeviceConfiguration();
    BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
    Graphics2D g = result.createGraphics();
    g.translate((neww - w) / 2, (newh - h) / 2);
    g.rotate(angle, w / 2, h / 2);/*from  w w  w . j a  va  2  s. co m*/
    g.drawRenderedImage(image, null);
    g.dispose();
    this.setProfilePicture(bundesbruder, this.storeImageToByteArray(image));
}

From source file:info.joseluismartin.gtc.WmsCache.java

/**
 * {@inheritDoc}//w  ww . j  ava 2  s .c o m
 */
@Override
protected String getCachePath(Tile tile) {
    WmsTile t = (WmsTile) tile;
    Bbox b = t.getBbox();
    int Z = 100;
    int P = 18000;
    int left = P + (int) Math.floor(b.getLeft() * Z);
    int up = P + (int) Math.floor(b.getUp() * Z);
    int right = P + (int) Math.floor(b.getRight() * Z);
    int down = P + (int) Math.floor(b.getDown() * Z);

    StringBuilder sb = new StringBuilder();
    sb.append(getCachePath());
    sb.append(File.separator);
    sb.append(getPath());
    sb.append(File.separator);
    sb.append(t.getSrs());
    sb.append(File.separator);
    if (!StringUtils.isBlank(t.getStyles()))
        sb.append(t.getStyles());
    sb.append(File.separator);
    if (!StringUtils.isBlank(t.getLayers()))
        sb.append(t.getLayers());
    sb.append(File.separator);
    sb.append(right);
    sb.append(File.separator);
    sb.append(down);
    sb.append(File.separator);
    sb.append(left);
    sb.append(File.separator);
    sb.append(up);
    sb.append(File.separator);
    sb.append(Integer.toHexString((t.getBbox().hashCode())));
    sb.append("_");
    sb.append(t.isTransparent() ? "t" : "o");
    sb.append(".");
    sb.append(t.getFileExension());

    return sb.toString();
}

From source file:com.arcao.geocaching.api.data.coordinates.CoordinatesParser.java

/**
 * Normalizes any number to an arbitrary range by assuming the range wraps around when going below min or above max
 * @param value input//  w w w. j a  v  a  2 s . c  om
 * @param start range start
 * @param end range end
 * @return normalized number
 */
protected static double normalize(double value, double start, double end) {
    final double width = end - start;
    final double offsetValue = value - start; // value relative to 0

    return (offsetValue - (Math.floor(offsetValue / width) * width)) + start; // + start to reset back to start of original range
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.dns.ZoneManager.java

protected static void initZoneCache(final TrafficRouter tr) {
    synchronized (ZoneManager.class) {
        final CacheRegister cacheRegister = tr.getCacheRegister();
        final JSONObject config = cacheRegister.getConfig();

        int poolSize = 1;
        final double scale = config.optDouble("zonemanager.threadpool.scale", 0.75);
        final int cores = Runtime.getRuntime().availableProcessors();

        if (cores > 2) {
            final Double s = Math.floor((double) cores * scale);

            if (s.intValue() > 1) {
                poolSize = s.intValue();
            }/*w w  w  .ja  va 2  s.  co m*/
        }

        final ExecutorService initExecutor = Executors.newFixedThreadPool(poolSize);

        final ExecutorService ze = Executors.newFixedThreadPool(poolSize);
        final ScheduledExecutorService me = Executors.newScheduledThreadPool(2); // 2 threads, one for static, one for dynamic, threads to refresh zones
        final int maintenanceInterval = config.optInt("zonemanager.cache.maintenance.interval", 300); // default 5 minutes
        final String dspec = "expireAfterAccess="
                + config.optString("zonemanager.dynamic.response.expiration", "300s"); // default to 5 minutes

        final LoadingCache<ZoneKey, Zone> dzc = createZoneCache(ZoneCacheType.DYNAMIC,
                CacheBuilderSpec.parse(dspec));
        final LoadingCache<ZoneKey, Zone> zc = createZoneCache(ZoneCacheType.STATIC);

        initZoneDirectory();

        try {
            LOGGER.info("Generating zone data");
            generateZones(tr, zc, dzc, initExecutor);
            initExecutor.shutdown();
            initExecutor.awaitTermination(5, TimeUnit.MINUTES);
            LOGGER.info("Zone generation complete");
        } catch (final InterruptedException ex) {
            LOGGER.warn("Initialization of zone data exceeded time limit of 5 minutes; continuing", ex);
        } catch (IOException ex) {
            LOGGER.fatal("Caught fatal exception while generating zone data!", ex);
        }

        me.scheduleWithFixedDelay(getMaintenanceRunnable(dzc, ZoneCacheType.DYNAMIC, maintenanceInterval), 0,
                maintenanceInterval, TimeUnit.SECONDS);
        me.scheduleWithFixedDelay(getMaintenanceRunnable(zc, ZoneCacheType.STATIC, maintenanceInterval), 0,
                maintenanceInterval, TimeUnit.SECONDS);

        final ExecutorService tze = ZoneManager.zoneExecutor;
        final ScheduledExecutorService tme = ZoneManager.zoneMaintenanceExecutor;
        final LoadingCache<ZoneKey, Zone> tzc = ZoneManager.zoneCache;
        final LoadingCache<ZoneKey, Zone> tdzc = ZoneManager.dynamicZoneCache;

        ZoneManager.zoneExecutor = ze;
        ZoneManager.zoneMaintenanceExecutor = me;
        ZoneManager.dynamicZoneCache = dzc;
        ZoneManager.zoneCache = zc;

        if (tze != null) {
            tze.shutdownNow();
        }

        if (tme != null) {
            tme.shutdownNow();
        }

        if (tzc != null) {
            tzc.invalidateAll();
        }

        if (tdzc != null) {
            tdzc.invalidateAll();
        }
    }
}

From source file:gov.sandia.umf.platform.ui.jobs.Raster.java

public JFreeChart createChart(final XYDataset dataset) {
    final JFreeChart chart = ChartFactory.createScatterPlot(null, // chart title
            null, // x axis label
            null, // y axis label
            dataset, // data
            PlotOrientation.VERTICAL, false, // include legend
            true, // tooltips
            false // urls
    );/*w  w w. ja  v  a 2 s  .  c o  m*/

    chart.setBackgroundPaint(Color.white);

    XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setDomainPannable(true);
    plot.setRangePannable(true);

    plot.setRenderer(new XYDotRenderer() {
        public void drawItem(java.awt.Graphics2D g2, XYItemRendererState state,
                java.awt.geom.Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis,
                ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState,
                int pass) {
            // Copied from org.jfree.chart.renderer.xy.XYDotRenderer.java and modified.
            // This would only need to be a couple of lines if they authors of jfreechart had not made dotWidth and dotHeight private members.
            // Yet another example of textbook OO programming gone awry. (Can anyone hear me scream?)

            if (!getItemVisible(series, item))
                return;

            int dotWidth = 1;

            double rasterLines = rangeAxis.getRange().getLength();
            int pixels = g2.getClipBounds().height;
            double height = pixels / rasterLines;
            if (height > 10)
                height -= 2;
            else if (height > 2)
                height -= 1;
            int dotHeight = (int) Math.min(20, Math.max(1, Math.floor(height)));

            double x = dataset.getXValue(series, item);
            double y = dataset.getYValue(series, item);
            if (Double.isNaN(y))
                return;
            double adjx = (dotWidth - 1) / 2.0;
            double adjy = (dotHeight - 1) / 2.0;

            RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
            RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
            double transX = domainAxis.valueToJava2D(x, dataArea, xAxisLocation) - adjx;
            double transY = rangeAxis.valueToJava2D(y, dataArea, yAxisLocation) - adjy;

            g2.setPaint(Color.black);
            PlotOrientation orientation = plot.getOrientation();
            if (orientation == PlotOrientation.HORIZONTAL)
                g2.fillRect((int) transY, (int) transX, dotHeight, dotWidth);
            else
                g2.fillRect((int) transX, (int) transY, dotWidth, dotHeight);

            int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
            int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
            updateCrosshairValues(crosshairState, x, y, domainAxisIndex, rangeAxisIndex, transX, transY,
                    orientation);
        }
    });

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); // Integer units only

    return chart;
}

From source file:Game.Player.java

private int handleVictoryRewardCase(JSONObject behaviour) {
    if (behaviour.getString("type").equals("victory_gain")) {
        if (behaviour.getString("amount").equals("based_on_deck")) {

            int frac = Integer.parseInt(behaviour.getString("fraction"));
            int decksize = numberOfTotalCards();

            if (behaviour.getString("rounding").equals("down")) {
                return (int) Math.floor(decksize / frac);
            } else {
                return (int) Math.ceil(decksize / frac);
            }/*from  w  w w  . j  av a  2s.  c  om*/
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

From source file:org.matsim.contrib.dvrp.util.chart.ScheduleCharts.java

private static TaskSeriesCollection createScheduleDataset(Collection<? extends Vehicle> vehicles,
        DescriptionCreator descriptionCreator) {
    TaskSeriesCollection collection = new TaskSeriesCollection();

    for (Vehicle v : vehicles) {
        Schedule schedule = v.getSchedule();

        final TaskSeries scheduleTaskSeries = new TaskSeries(v.getId().toString());

        if (schedule.getStatus() == ScheduleStatus.UNPLANNED) {
            collection.add(scheduleTaskSeries);
            continue;
        }//ww  w  . j  a v a  2 s.c  o m

        for (Task t : schedule.getTasks()) {
            String description = descriptionCreator.create(t);

            TimePeriod duration = new SimpleTimePeriod(//
                    new Date((int) Math.floor(t.getBeginTime() * 1000)), //
                    new Date((int) Math.ceil(t.getEndTime() * 1000)));

            scheduleTaskSeries.add(new ChartTask(description, duration, t));
        }

        collection.add(scheduleTaskSeries);
    }

    return collection;
}

From source file:su.fmi.photoshareclient.remote.ImageHandler.java

public static ArrayList<ImageLabel> getImages() {
    ProjectProperties props = new ProjectProperties();
    String webPage = "http://" + props.get("socket") + props.get("restEndpoint") + "/image";
    URL url;/*from  w  w w .j a v  a 2s. c  om*/
    try {
        url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + LoginHandler.getAuthStringEncripted());
        InputStream is = urlConnection.getInputStream();

        InputStreamReader isr = new InputStreamReader(is);

        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();
        Gson gson = new Gson();

        RemoteImage[] remoteImages = gson.fromJson(result, RemoteImage[].class);

        ArrayList<ImageLabel> images = new ArrayList<ImageLabel>();
        Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        for (RemoteImage rimg : remoteImages) {
            ImageLabel img = getImage(rimg.id, rimg.fileName);
            int imageWidth = img.getImage().getWidth(null);
            int imageHeight = img.getImage().getHeight(null);
            // just a relative estimation
            int imagesPerColumn = (int) Math.floor(Math.sqrt(Pagination.getImagesPerPage()));
            double ratio = (screenSize.height / (double) imageHeight < screenSize.width / (double) imageWidth)
                    ? screenSize.height / (double) imageHeight
                    : screenSize.width / (double) imageWidth;
            ratio = ratio / imagesPerColumn; // reduce ratio because more than 1 image are located in the column
            int resizeWidth = (int) (imageWidth * ratio);
            int resizeHeight = (int) (imageHeight * ratio);
            Image resizedImage = createResizedCopy(img.getImage(), resizeWidth, resizeHeight, false);
            images.add(new ImageLabel(resizedImage, img.getImageId(), img.getFileName()));
        }
        return images;
    } catch (MalformedURLException ex) {
        System.out.println(ex);
    } catch (IOException ex) {
        System.out.println(ex);
    }

    return null;
}