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

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

Introduction

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

Prototype

@GwtIncompatible("#roundIntermediate")
public static long roundToLong(double x, RoundingMode mode) 

Source Link

Document

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

Usage

From source file:org.ldp4j.http.DoubleUtils.java

static double limitPrecision(final double value, final int decimals) {
    final double scale = scale(decimals);
    final long scaledValue = DoubleMath.roundToLong(value * scale, RoundingMode.HALF_EVEN);
    return ((double) scaledValue) / scale;
}

From source file:org.terasology.world.time.WorldTimeEvent.java

public boolean matchesDaily(float fraction) {
    Preconditions.checkArgument(fraction >= 0 && fraction <= 1, "fraction must be in [0..1]");

    long fracInMs = DoubleMath.roundToLong(fraction * WorldTime.DAY_LENGTH, RoundingMode.HALF_UP);
    long diff = getDayTimeInMs() - fracInMs;

    return 2 * diff < WorldTime.TICK_EVENT_RATE && 2 * diff >= -WorldTime.TICK_EVENT_RATE;
}

From source file:org.terasology.weatherManager.systems.WeatherManagerSystem.java

@Override
public void postBegin() {
    logger.info("Initializing WeatherManSystem");

    float avglength = WorldTime.DAY_LENGTH / 480.0f;// / 48.0f; // worldTime.getTimeRate(); -- not available for modules
    weatherConditionProvider = new MarkovChainWeatherGenerator(12354, avglength);
    current = weatherConditionProvider.getNext();

    EntityRef weatherEntity = entityManager.create();

    long length = DoubleMath.roundToLong(current.duration, RoundingMode.HALF_UP);
    delayManager.addDelayedAction(weatherEntity, "Weather", length);

    logger.info("Current weather: " + current.condition + " (" + current.duration + ")");
}

From source file:com.github.rinde.gpem17.eval.SimRuntimeLogger.java

void write() {
    lastWrite = System.currentTimeMillis();
    StringBuilder sb = new StringBuilder();
    String timestamp = ISODateTimeFormat.dateHourMinuteSecond().print(lastWrite);

    long sum = 0;
    double[] arr = new double[receivedResults.size()];
    for (int i = 0; i < receivedResults.size(); i++) {
        SimResult info = (SimResult) receivedResults.get(i).getResultObject();
        sum += info.getStats().computationTime;
        arr[i] = info.getStats().computationTime;
    }// ww  w  .ja v a2  s .  c o  m
    double mean = sum / receivedResults.size();
    long sd = DoubleMath.roundToLong(new StandardDeviation().evaluate(arr, mean), RoundingMode.HALF_DOWN);
    long longMean = DoubleMath.roundToLong(mean, RoundingMode.HALF_DOWN);

    sb.append(timestamp).append(",").append(receivedSims).append("/").append(totalSims).append(", Received ")
            .append(receivedResults.size()).append(" results in last minute, avg comp time,")
            .append(PeriodFormat.getDefault().print(new Period(longMean))).append(", standard deviation,")
            .append(PeriodFormat.getDefault().print(new Period(sd))).append(System.lineSeparator());
    try {
        Files.append(sb.toString(), progressFile, Charsets.UTF_8);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    receivedResults.clear();
}

From source file:gobblin.source.extractor.watermark.SimpleWatermark.java

/**
 * recalculate interval if total number of partitions greater than maximum number of allowed partitions
 *
 * @param low watermark value/*from ww w  . j av a 2 s  .  co  m*/
 * @param high watermark value
 * @param partition interval
 * @param Maximum number of allowed partitions
 * @return calculated interval
 */
private static long getInterval(long lowWatermarkValue, long highWatermarkValue, long partitionInterval,
        int maxIntervals) {
    if (lowWatermarkValue > highWatermarkValue) {
        LOG.info("lowWatermarkValue: " + lowWatermarkValue + " is greater than highWatermarkValue: "
                + highWatermarkValue);

        return 0;
    }
    long outputInterval = partitionInterval;
    boolean longOverflow = false;
    long totalIntervals = Long.MAX_VALUE;
    try {
        totalIntervals = DoubleMath.roundToLong((double) highWatermarkValue / partitionInterval
                - (double) lowWatermarkValue / partitionInterval, RoundingMode.CEILING);
    } catch (java.lang.ArithmeticException e) {
        longOverflow = true;
    }
    if (longOverflow || totalIntervals > maxIntervals) {
        outputInterval = DoubleMath.roundToLong(
                (double) highWatermarkValue / maxIntervals - (double) lowWatermarkValue / maxIntervals,
                RoundingMode.CEILING);

    }
    return outputInterval;
}

From source file:org.terasology.musicdirector.TimedTriggerSystem.java

public boolean isTriggered(TimedMusicTriggerComponent trigger) {

    long time = worldTime.getMilliseconds();
    long timeInDay = LongMath.mod(time, WorldTime.DAY_LENGTH);

    long startInMs = DoubleMath.roundToLong(trigger.dailyStart * WorldTime.DAY_LENGTH, RoundingMode.HALF_UP);
    long endInMs = DoubleMath.roundToLong(trigger.dailyEnd * WorldTime.DAY_LENGTH, RoundingMode.HALF_UP);

    if (startInMs < endInMs) {
        // -----[xxxxxxxxxx]------
        return timeInDay >= startInMs && timeInDay <= endInMs;
    } else {//www  . j av  a  2  s. com
        // xxxxx]----------[xxxxxx
        return timeInDay >= startInMs || timeInDay <= endInMs;
    }
}

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

/**
 * Calculates how many buckets are needed to hold the chosen number of keys,
 * taking the standard load factor into account.
 * //w ww .ja  va2  s.c om
 * @param maxKeys
 *            the number of keys the filter is expected to hold before
 *            insertion failure.
 * @return The number of buckets needed
 */
static long getBucketsNeeded(long maxKeys, double loadFactor, int bucketSize) {
    /*
     * force a power-of-two bucket count so hash functions for bucket index
     * can hashBits%numBuckets and get randomly distributed index. See wiki
     * "Modulo Bias". Only time we can get perfectly distributed index is
     * when numBuckets is a power of 2.
     */
    long bucketsNeeded = DoubleMath.roundToLong((1.0 / loadFactor) * maxKeys / bucketSize, RoundingMode.UP);
    // get next biggest power of 2
    long bitPos = Long.highestOneBit(bucketsNeeded);
    if (bucketsNeeded > bitPos)
        bitPos = bitPos << 1;
    return bitPos;
}

From source file:com.github.rinde.logistics.pdptw.solver.optaplanner.Vehicle.java

public long computeTravelTime(Point from, Point to) {
    final double speedKMH = vehicle.getDto().getSpeed();

    final double distKM = Point.distance(from, to);

    final double travelTimeH = distKM / speedKMH;
    // convert to nanoseconds
    return DoubleMath.roundToLong(travelTimeH * H_TO_NS, RoundingMode.HALF_DOWN);
}

From source file:at.ac.univie.isc.asio.tool.JvmOptions.java

private String[] heap() {
    if (relativeHeapSize < 0) {
        return new String[0];
    }//from   w ww  . j a  v a 2 s . com
    final long total = system.getTotalMemory() / MEBI_BYTE;
    final long heap = DoubleMath.roundToLong(total * relativeHeapSize, RoundingMode.UP);
    final long free = system.getFreeMemory() / MEBI_BYTE;
    log.debug("using {}MiB as heap size (~{}% of total {}Mib)", heap, relativeHeapSize * 100, total);
    if (heap > free) {
        log.error("calculated heap size of {}MiB is greater than current free amount of memory ({}MiB)", heap,
                free);
    }
    final String metaSpaceArg = system.getJvmSpecVersion() > 7
            ? "-XX:MaxMetaspaceSize=" + DoubleMath.roundToLong(total * 0.5, RoundingMode.CEILING)
            : "-XX:MaxPermSize=" + Math.max(128, DoubleMath.roundToLong(total * 0.05, RoundingMode.CEILING));
    return new String[] { "-Xms" + heap + "M", "-Xmx" + heap + "M", metaSpaceArg };
}

From source file:veloziped.ws1516.articles.ExtendedArticle.java

public long getDeliveryTimeFastInDays(CalculationMode mode) {
    if (null == mode) {
        return 0;
    }/*from ww  w.  ja  va 2s  .  c om*/

    //half time of deliver time without deviation
    double deliverFast = (this.deliverTime / 2) * 5;
    //1 day moving to warehouse
    switch (mode) {
    case OPTIMISTIC:
        return DoubleMath.roundToLong(deliverFast, RoundingMode.DOWN) + 1;
    case PESSIMISTIC:
        return DoubleMath.roundToLong(deliverFast, RoundingMode.CEILING) + 1;
    default:
        return 0;
    }
}