Example usage for com.google.common.math DoubleMath roundToInt

List of usage examples for com.google.common.math DoubleMath roundToInt

Introduction

In this page you can find the example usage for com.google.common.math DoubleMath roundToInt.

Prototype

@GwtIncompatible("#roundIntermediate")
public static int roundToInt(double x, RoundingMode mode) 

Source Link

Document

Returns the int value that is equal to x rounded with the specified rounding mode, if possible.

Usage

From source file:org.terasology.polyworld.voronoi.VoronoiGraph.java

public VoronoiGraph(Voronoi ov, int numLloydRelaxations) {
    Voronoi v = ov;//from   ww w.  j av a 2 s  . c  o m

    int minX = DoubleMath.roundToInt(ov.getPlotBounds().minX(), RoundingMode.FLOOR);
    int minY = DoubleMath.roundToInt(ov.getPlotBounds().minY(), RoundingMode.FLOOR);
    int width = DoubleMath.roundToInt(ov.getPlotBounds().width(), RoundingMode.CEILING);
    int height = DoubleMath.roundToInt(ov.getPlotBounds().height(), RoundingMode.CEILING);

    bounds = Rect2i.createFromMinAndSize(minX, minY, width, height);

    for (int i = 0; i < numLloydRelaxations; i++) {
        List<Vector2f> points = v.siteCoords();
        for (Vector2f p : points) {
            List<Vector2f> region = v.region(p);
            float x = 0;
            float y = 0;
            for (Vector2f c : region) {
                x += c.getX();
                y += c.getY();
            }
            x /= region.size();
            y /= region.size();
            p.setX(x);
            p.setY(y);
        }
        v = new Voronoi(points, v.getPlotBounds());
    }
    buildGraph(v);
}

From source file:com.github.rinde.rinsim.pdptw.common.ScenarioTestUtil.java

/**
 * Creates a random scenario.//w  w w  .  ja v a2  s  .c  o  m
 * @param seed The seed to use.
 * @param models Additional models (optional).
 * @return A new random scenario.
 */
public static Scenario createRandomScenario(long seed, ModelBuilder<?, ?>... models) {
    final int endTime = 3 * 60 * 60 * 1000;
    final Scenario.Builder b = Scenario.builder().addModel(RoadModelBuilders.plane())
            .addModel(DefaultPDPModel.builder()).addModels(asList(models)).addEvents(Collections.nCopies(10,
                    AddVehicleEvent.create(-1, VehicleDTO.builder().startPosition(new Point(5, 5)).build())));

    final RandomGenerator rng = new MersenneTwister(seed);
    for (int i = 0; i < 20; i++) {
        final long announceTime = rng.nextInt(DoubleMath.roundToInt(endTime * .8, RoundingMode.FLOOR));
        b.addEvent(AddParcelEvent.create(Parcel
                .builder(new Point(rng.nextDouble() * 10, rng.nextDouble() * 10),
                        new Point(rng.nextDouble() * 10, rng.nextDouble() * 10))
                .orderAnnounceTime(announceTime).pickupTimeWindow(TimeWindow.create(announceTime, endTime))
                .deliveryTimeWindow(TimeWindow.create(announceTime, endTime)).neededCapacity(0).buildDTO()));
    }

    b.addEvent(TimeOutEvent.create(endTime)).scenarioLength(endTime)
            .setStopCondition(StopConditions.limitedTime(endTime));

    return b.build();
}

From source file:org.eclipse.hawkbit.repository.jpa.cache.CacheWriteNotify.java

/**
 * writes the download progress into the cache
 * {@link CacheKeys#DOWNLOAD_PROGRESS_PERCENT} and notifies the
 * {@link EventBus} with a {@link DownloadProgressEvent}.
 * /*from  w  w  w  . jav a  2  s. com*/
 * @param statusId
 *            the ID of the {@link ActionStatus}
 * @param requestedBytes
 *            requested bytes of the request
 * @param shippedBytesSinceLast
 *            since last event
 * @param shippedBytesOverall
 *            for the download request
 */
public void downloadProgress(final Long statusId, final Long requestedBytes, final Long shippedBytesSinceLast,
        final Long shippedBytesOverall) {

    final Cache cache = cacheManager.getCache(ActionStatus.class.getName());
    final String cacheKey = CacheKeys.entitySpecificCacheKey(String.valueOf(statusId),
            CacheKeys.DOWNLOAD_PROGRESS_PERCENT);

    final int progressPercent = DoubleMath.roundToInt(shippedBytesOverall * 100.0 / requestedBytes,
            RoundingMode.DOWN);

    if (progressPercent < DOWNLOAD_PROGRESS_MAX) {
        cache.put(cacheKey, progressPercent);
    } else {
        // in case we reached progress 100 delete the cache value again
        // because otherwise he will
        // keep there forever
        cache.evict(cacheKey);
    }

    eventBus.post(new DownloadProgressEvent(tenantAware.getCurrentTenant(), statusId, requestedBytes,
            shippedBytesSinceLast, shippedBytesOverall));
}

From source file:org.terasology.StaticCities.roof.PentRoofRasterizer.java

@Override
public void raster(RasterTarget target, PentRoof roof, HeightMap hm) {
    Rect2i area = roof.getArea();// w w w.j a va  2  s. c om

    if (!area.overlaps(target.getAffectedArea())) {
        return;
    }

    final HeightMap hmBottom = new HeightMap() {

        @Override
        public int apply(int x, int z) {
            int rx = x - area.minX();
            int rz = z - area.minY();

            BaseVector2i dir = roof.getOrientation().getDir();

            if (dir.getX() < 0) {
                rx -= area.width() - 1; // maxX
            }

            if (dir.getY() < 0) {
                rz -= area.height() - 1; // maxY
            }

            int hx = rx * dir.getX();
            int hz = rz * dir.getY();

            int h = DoubleMath.roundToInt(Math.max(hx, hz) * roof.getPitch(), RoundingMode.HALF_UP);

            return roof.getBaseHeight() + h;
        }
    };

    int thickness = TeraMath.ceilToInt(roof.getPitch());
    HeightMap hmTop = HeightMaps.offset(hmBottom, thickness);
    Pen pen = Pens.fill(target, hmBottom, hmTop, DefaultBlockType.ROOF_HIP);
    RasterUtil.fillRect(pen, area);

    final Rect2i wallRect = roof.getBaseArea();

    HeightMap hmGableBottom = new HeightMap() {

        @Override
        public int apply(int x, int z) {
            int h0 = roof.getBaseHeight();

            boolean onZ = (x == wallRect.minX() || x == wallRect.maxX());
            boolean zOk = (z >= wallRect.minY() && z <= wallRect.maxY());

            if (onZ && zOk) {
                return h0;
            }

            boolean onX = (z == wallRect.minY() || z == wallRect.maxY());
            boolean xOk = (x >= wallRect.minX() && x <= wallRect.maxX());

            if (onX && xOk) {
                return h0;
            }

            return hmBottom.apply(x, z); // return top-height to get a no-op
        }
    };

    pen = Pens.fill(target, hmGableBottom, hmBottom, DefaultBlockType.ROOF_GABLE);
    RasterUtil.fillRect(pen, area);
}

From source file:org.terasology.dynamicCities.rasterizer.parts.HollowBuildingPartRasterizer.java

@Override
protected void raster(RasterTarget brush, HollowBuildingPart part, HeightMap heightMap) {
    Rect2i rc = part.getShape();/*from   w w w . j  a v  a 2  s .  co  m*/

    if (!rc.overlaps(brush.getAffectedArea())) {
        return;
    }

    //      TODO: check y overlap

    int baseHeight = part.getBaseHeight();
    int wallHeight = part.getWallHeight();
    int arcRadius = part.getArcRadius();

    Pen floorPen = BuildingPens.floorPen(brush, heightMap, baseHeight, DefaultBlockType.BUILDING_FLOOR);
    RasterUtil.fillRect(floorPen, rc);

    HeightMap hmTop = HeightMaps.constant(baseHeight + wallHeight);
    HeightMap hmBottom = new HeightMap() {

        @Override
        public int apply(int x, int z) {

            int distToCornerSq = Edges.getDistanceToCornerSq(rc, x, z);
            if (distToCornerSq == 0) {
                return baseHeight;
            }

            int top = hmTop.apply(x, z);
            int arcSq = arcRadius * arcRadius;
            int dxSq = Math.max(0, arcSq - distToCornerSq);
            int dy = DoubleMath.roundToInt(Math.sqrt(arcSq - dxSq), RoundingMode.HALF_UP);
            return top - arcRadius + dy;
        }

    };

    // create walls
    Pen wallPen = Pens.fill(brush, hmBottom, hmTop, DefaultBlockType.BUILDING_WALL);
    RasterUtil.drawRect(wallPen, rc);
}

From source file:com.github.mgunlogson.cuckoofilter4j.Utils.java

/**
 * Calculates how many bits are needed to reach a given false positive rate.
 * //w  w  w.  j a v  a 2 s  . c o  m
 * @param fpProb
 *            the false positive probability.
 * @return the length of the tag needed (in bits) to reach the false
 *         positive rate.
 */
static int getBitsPerItemForFpRate(double fpProb, double loadFactor) {
    /*
     * equation from Cuckoo Filter: Practically Better Than Bloom Bin Fan,
     * David G. Andersen, Michael Kaminsky , Michael D. Mitzenmacher
     */
    return DoubleMath.roundToInt(DoubleMath.log2((1 / fpProb) + 3) / loadFactor, RoundingMode.UP);
}

From source file:org.terasology.StaticCities.walls.TownWallRasterizer.java

private void rasterSolid(RasterTarget target, SolidWallSegment element, HeightMap hm) {

    int x1 = element.getStart().getX();
    int z1 = element.getStart().getY();
    int y1 = hm.apply(x1, z1) + element.getWallHeight();
    int x2 = element.getEnd().getX();
    int z2 = element.getEnd().getY();
    int y2 = hm.apply(x2, z2) + element.getWallHeight();

    Ramp ramp = new Ramp(x1, y1, z1, x2, y2, z2);

    HeightMap topHm = new HeightMap() {

        @Override/*from   w w  w . jav a 2s  . c  o  m*/
        public int apply(int x, int z) {
            float y = ramp.getY(x, z);
            return DoubleMath.roundToInt(y, RoundingMode.HALF_UP);
        }
    };

    Pen pen = Pens.fill(target, hm, topHm, DefaultBlockType.TOWER_WALL);
    RasterUtil.drawLine(pen, new LineSegment(x1, z1, x2, z2));
}

From source file:org.terasology.rendering.nui.layers.mainMenu.PlayerSettingsScreen.java

private Color findClosestColor(float findex) {
    int index = DoubleMath.roundToInt(findex * (colors.size() - 1), RoundingMode.HALF_UP);
    Color color = colors.get(index);
    return color;
}

From source file:com.ibm.og.scheduling.RequestRateScheduler.java

/**
 * Constructs an instance using the provided rate {@code count / unit }
 * /*w w  w.  j  a  v a  2 s.  c  om*/
 * @param rate the numerator of the rate to configure
 * @param unit the denominator of the rate to configure
 * @param rampup the duration to ramp up to the stable request rate
 * @param rampupUnit the rampup duration unit
 */
public RequestRateScheduler(final double rate, final TimeUnit unit, final double rampup,
        final TimeUnit rampupUnit) {
    checkArgument(rate >= 0.0, "rate must be >= 0.0 [%s]", rate);
    this.rate = rate;
    this.unit = checkNotNull(unit);
    checkArgument(rampup >= 0.0, "rampup must be >= 0.0 [%s]", rampup);
    this.rampup = rampup;
    this.rampupUnit = checkNotNull(rampupUnit);
    this.permits = new AtomicReference<RateLimiter>();

    // convert arbitrary rate unit to rate/second
    final double requestsPerSecond = requestsPerSecond(rate, unit);

    _logger.debug("Calculated requests per second [{}]", requestsPerSecond);

    if (DoubleMath.fuzzyEquals(rampup, 0.0, Math.pow(0.1, 6))) {
        final RateLimiter steady = RateLimiter.create(requestsPerSecond);
        this.permits.set(steady);
    } else {
        // the warmup Ratelimiter will not work if the permit request rate is slow enough to not being able to reach the
        // threshold from left. The permits are accumulated faster than the request rate here.
        // So the steady OPS will not be reached at all during warm up period.
        // Approximate the warm-up period with steady ratelimiter and set the ops for the steady rate limiter
        // based on the steady state ops, warm up duration.

        // calculate the ops based on the ramp duration and steady state ops
        final double slope = requestsPerSecond / (rampupUnit.toSeconds((long) rampup));
        final int rampStepWidth = calculateStepWidth(rate, rampup, rampupUnit);

        this.permits.set(RateLimiter.create(slope * rampStepWidth * 1));

        final Thread rampupThread = new Thread(new Runnable() {
            @Override
            public void run() {
                _logger.debug("Awaiting start latch");
                Uninterruptibles.awaitUninterruptibly(RequestRateScheduler.this.started);

                _logger.info("Starting ramp");

                double requestsPerSecondNow;
                RateLimiter rampRateLimiter;
                int rampStepNum = 1;
                int rampSteps = DoubleMath.roundToInt(((rampupUnit.toSeconds((long) rampup)) / rampStepWidth),
                        RoundingMode.DOWN);
                _logger.info("ramp profile rampStepWidth {}  NumRampSteps {} ", rampStepWidth, rampSteps);
                while (rampStepNum <= rampSteps) {
                    Uninterruptibles.sleepUninterruptibly(rampStepWidth * 1000L, TimeUnit.MILLISECONDS);
                    rampStepNum++;
                    requestsPerSecondNow = slope * rampStepWidth * rampStepNum;
                    _logger.debug("slope {} rampStep  {}  targetRequestPerSecond {} ", slope, rampStepNum,
                            requestsPerSecondNow);
                    rampRateLimiter = RateLimiter.create(requestsPerSecondNow);
                    RequestRateScheduler.this.permits.set(rampRateLimiter);
                }
                final RateLimiter steady = RateLimiter.create(requestsPerSecond);
                RequestRateScheduler.this.permits.set(steady);

                _logger.info("Finished ramp");
            }

        }, "rate-scheduler-ramp");
        rampupThread.setDaemon(true);
        rampupThread.start();
    }
    this.started = new CountDownLatch(1);
}

From source file:edu.mit.streamjit.impl.compiler2.DescendingShareAllocationStrategy.java

@Override
public void allocateGroup(ActorGroup group, Range<Integer> iterations, List<Core> cores, Configuration config) {
    List<Float> shares = new ArrayList<>(cores.size());
    for (int core = 0; core < cores.size(); ++core) {
        String name = String.format("node%dcore%diter", group.id(), core);
        Configuration.FloatParameter parameter = config.getParameter(name, Configuration.FloatParameter.class);
        if (parameter == null)
            shares.add(0f);/*from   w ww .j ava  2s  . c  o  m*/
        else
            shares.add(parameter.getValue());
    }

    assert iterations.lowerBoundType() == BoundType.CLOSED && iterations.upperBoundType() == BoundType.OPEN;
    int totalAvailable = iterations.upperEndpoint() - iterations.lowerEndpoint();
    while (!iterations.isEmpty()) {
        int max = CollectionUtils.maxIndex(shares);
        float share = shares.get(max);
        if (share == 0)
            break;
        int amount = DoubleMath.roundToInt(share * totalAvailable, RoundingMode.HALF_EVEN);
        int done = iterations.lowerEndpoint();
        Range<Integer> allocation = group.isStateful() ? iterations
                : iterations.intersection(Range.closedOpen(done, done + amount));
        cores.get(max).allocate(group, allocation);
        iterations = Range.closedOpen(allocation.upperEndpoint(), iterations.upperEndpoint());
        shares.set(max, 0f); //don't allocate to this core again
    }

    //If we have iterations left over not assigned to a core, spread them
    //evenly over all cores.
    if (!iterations.isEmpty()) {
        int perCore = IntMath.divide(iterations.upperEndpoint() - iterations.lowerEndpoint(), cores.size(),
                RoundingMode.CEILING);
        for (int i = 0; i < cores.size() && !iterations.isEmpty(); ++i) {
            int min = iterations.lowerEndpoint();
            Range<Integer> allocation = group.isStateful() ? iterations
                    : iterations.intersection(Range.closedOpen(min, min + perCore));
            cores.get(i).allocate(group, allocation);
            iterations = Range.closedOpen(allocation.upperEndpoint(), iterations.upperEndpoint());
        }
    }
    assert iterations.isEmpty();
}