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:net.solarnetwork.node.control.demandbalancer.SimpleDemandBalanceStrategy.java

@Override
public int evaluateBalance(final String powerControlId, final int demandWatts, final int generationWatts,
        final int generationCapacityWatts, final int currentLimit) {
    int desiredLimit = currentLimit;
    if (demandWatts < 0) {
        // unknown demand... set to unknownDemandLimit
        desiredLimit = unknownDemandLimit;
    } else if (demandWatts < generationCapacityWatts) {
        // demand is less than generation capacity... enforce limit
        desiredLimit = (int) Math.floor(100.0 * demandWatts / generationCapacityWatts);
        log.debug("Demand of {} is less than {} capacity of {}, limiting to {}%", demandWatts, powerControlId,
                generationCapacityWatts, desiredLimit);
    } else {/*from www  . ja  v a  2  s  .co  m*/
        // go for it
        desiredLimit = 100;
    }
    return desiredLimit;
}

From source file:com.garyclayburg.UserRestSmokeTest.java

@Test
public void testHalJsonApache() throws Exception {
    RestTemplate rest = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    SimpleUser user1 = new SimpleUser();
    user1.setFirstname("Tommy");
    user1.setLastname("Deleteme");
    user1.setId("112" + (int) (Math.floor(Math.random() * 10000)));

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Content-Type", "application/hal+json");
    //        HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    HttpEntity<?> requestEntity = new HttpEntity(user1, requestHeaders);

    ResponseEntity<SimpleUser> simpleUserResponseEntity = rest.exchange(
            "http://" + endpoint + "/audited-users/auditedsave", HttpMethod.POST, requestEntity,
            SimpleUser.class);

    //        ResponseEntity<SimpleUser> userResponseEntity =
    //            rest.postForEntity("http://" + endpoint + "/audited-users/auditedsave",user1,SimpleUser.class);
    log.info("got a response");
    MatcherAssertionErrors.assertThat(simpleUserResponseEntity.getStatusCode(),
            Matchers.equalTo(HttpStatus.OK));

}

From source file:com.proofpoint.units.Duration.java

public long roundTo(TimeUnit timeUnit) {
    Preconditions.checkNotNull(timeUnit, "timeUnit is null");
    double rounded = Math.floor(getValue(timeUnit) + 0.5d);
    Preconditions.checkArgument(rounded <= Long.MAX_VALUE,
            "size is too large to be represented in requested unit as a long");
    return (long) rounded;
}

From source file:geogebra.kernel.statistics.AlgoRandomBinomial.java

private int randomBinomialTRS(int n, double p) {

    if (p > 0.5)
        return n - randomBinomialTRS(n, 1 - p);

    if (n * p < 10)
        return randomBinomial(n, p);

    double spq = Math.sqrt(n * p * (1 - p));

    double b = 1.15 + 2.53 * spq;
    double a = -0.0873 + 0.0248 * b + 0.01 * p;
    double c = n * p + 0.5;
    double v_r = 0.92 - 4.2 / b;

    double us = 0;
    double v = 0;

    while (true) {

        int k = -1;
        while (k < 0 || k > n) {
            double u = Math.random() - 0.5;
            v = Math.random();/* w w  w. j a v  a  2 s.  co  m*/
            us = 0.5 - Math.abs(u);
            k = (int) Math.floor((2 * a / us + b) * u + c);
            if (us >= 0.07 && v < v_r)
                return k;
        }

        double alpha = (2.83 + 5.1 / b) * spq;
        double lpq = Math.log(p / (1 - p));
        int m = (int) Math.floor((n + 1) * p);
        double h = logOfKFactorial(m) + logOfKFactorial((n - m));

        v = v * alpha / (a / (us * us) + b);

        if (v <= h - logOfKFactorial(k) - logOfKFactorial(n - k) + (k - m) * lpq)
            return k;
    }

}

From source file:hivemall.xgboost.classification.XGBoostMulticlassClassifierUDTF.java

@Override
protected void checkTargetValue(final double target) throws HiveException {
    double num_class = ((Integer) params.get("num_class")).doubleValue();
    if (target < 0.0 || target > num_class || Double.compare(target - Math.floor(target), 0.0) != 0) {
        throw new HiveException(
                "target must be {0.0, ..., " + String.format("%.1f", (num_class - 1.0)) + "}: " + target);
    }//from  w ww. j ava  2 s  . com
}

From source file:edu.asu.ca.kaushik.algorithms.twostage.group.Script.java

public GroupLLLCA firstStage(int t, int k, int v) {
    assert (k >= 2 * t);
    int n = this.partialArraySize(t, k, v);
    System.out.println("Target partial array size: " + n);
    int numMinUncovOrb = (int) Math.floor(this.expectNumUncovOrbs(t, k, v, n));
    numMinUncovOrb = (int) (1.0 + this.slackPercent / 100) * numMinUncovOrb;

    GroupLLLCA partialCa = new GroupLLLCA(t, k, v, n, this.gType, new Random());
    this.initSecondStage(t, k, v, partialCa.getGroup());
    ColGrIterator clGrIt = new ColGrLexIterator(t, k);
    int uncovOrbNum;
    int colGrNum;
    boolean enoughCovered;

    int iteration = 1;
    do {//from   w w w .j  a va 2 s . co m
        System.out.println("Iteration: " + iteration);
        colGrNum = 0;

        Set<Integer> badCols = new HashSet<Integer>();
        uncovOrbNum = 0;
        clGrIt.rewind();
        enoughCovered = true;
        while (clGrIt.hasNext()) {
            ColGroup cols = clGrIt.next();
            partialCa.resetCovered();
            List<Interaction> notCovered = partialCa.notCovered(cols);
            if (!notCovered.isEmpty()) {
                uncovOrbNum = uncovOrbNum + notCovered.size();
                this.addCols(badCols, cols);
                this.cover(notCovered);
            }
            if (uncovOrbNum > numMinUncovOrb) {
                this.reset();
                this.reSampleCols(partialCa, badCols, notCovered);
                enoughCovered = false;
                System.out.println("uncovered interaction in coloumn group: " + colGrNum);
                System.out.println(new Date());
                break;
            }
            colGrNum++;
        }
        iteration++;
    } while (!enoughCovered && iteration <= maxIteration);

    if (!enoughCovered) {
        System.out.println("output is not a covering array");
        //System.exit(1);
    }

    System.out.println("Number of uncovered orbits: " + uncovOrbNum);
    return partialCa;
}

From source file:com.shvet.poi.ss.format.SimpleFraction.java

/**
 * Create a fraction given the double value and either the maximum error
 * allowed or the maximum number of denominator digits.
 * <p>//from  w w  w .  j a  v a 2s.  c  o m
 * References:
 * <ul>
 * <li><a href="http://mathworld.wolfram.com/ContinuedFraction.html">
 * Continued Fraction</a> equations (11) and (22)-(26)</li>
 * </ul>
 * </p>
 * <p/>
 * Based on org.apache.commons.math.fraction.Fraction from Apache
 * Commons-Math. YK: The only reason of having this class is to avoid
 * dependency on the Commons-Math jar.
 *
 * @param value          the double value to convert to a fraction.
 * @param epsilon        maximum error allowed. The resulting fraction is within
 *                       <code>epsilon</code> of <code>value</code>, in absolute terms.
 * @param maxDenominator maximum denominator value allowed.
 * @param maxIterations  maximum number of convergents
 * @throws RuntimeException         if the continued fraction failed to converge.
 * @throws IllegalArgumentException if value > Integer.MAX_VALUE
 */
private static SimpleFraction buildFractionMaxDenominator(double value, double epsilon, int maxDenominator,
        int maxIterations) {
    long overflow = Integer.MAX_VALUE;
    double r0 = value;
    long a0 = (long) Math.floor(r0);
    if (a0 > overflow) {
        throw new IllegalArgumentException(
                "Overflow trying to convert " + value + " to fraction (" + a0 + "/" + 1l + ")");
    }

    // check for (almost) integer arguments, which should not go
    // to iterations.
    if (Math.abs(a0 - value) < epsilon) {
        return new SimpleFraction((int) a0, 1);
    }

    long p0 = 1;
    long q0 = 0;
    long p1 = a0;
    long q1 = 1;

    long p2;
    long q2;

    int n = 0;
    boolean stop = false;
    do {
        ++n;
        double r1 = 1.0 / (r0 - a0);
        long a1 = (long) Math.floor(r1);
        p2 = (a1 * p1) + p0;
        q2 = (a1 * q1) + q0;
        // MATH-996/POI-55419
        if (epsilon == 0.0f && maxDenominator > 0 && Math.abs(q2) > maxDenominator
                && Math.abs(q1) < maxDenominator) {

            return new SimpleFraction((int) p1, (int) q1);
        }
        if ((p2 > overflow) || (q2 > overflow)) {
            throw new RuntimeException(
                    "Overflow trying to convert " + value + " to fraction (" + p2 + "/" + q2 + ")");
        }

        double convergent = (double) p2 / (double) q2;
        if (n < maxIterations && Math.abs(convergent - value) > epsilon && q2 < maxDenominator) {
            p0 = p1;
            p1 = p2;
            q0 = q1;
            q1 = q2;
            a0 = a1;
            r0 = r1;
        } else {
            stop = true;
        }
    } while (!stop);

    if (n >= maxIterations) {
        throw new RuntimeException(
                "Unable to convert " + value + " to fraction after " + maxIterations + " iterations");
    }

    if (q2 < maxDenominator) {
        return new SimpleFraction((int) p2, (int) q2);
    } else {
        return new SimpleFraction((int) p1, (int) q1);
    }

}

From source file:net.sf.jtmt.clustering.SimulatedAnnealingClusterer.java

/**
 * Cluster./*from w w  w.j av  a  2 s .  co  m*/
 *
 * @param collection the collection
 * @return the list
 */
public List<Cluster> cluster(DocumentCollection collection) {
    // 1) Get initial set of clusters... 
    int numDocs = collection.size();
    int numClusters = (int) Math.floor(Math.sqrt(numDocs));
    List<Cluster> clusters = new ArrayList<Cluster>();
    for (int i = 0; i < numClusters; i++) {
        clusters.add(new Cluster("C" + i));
    }
    // ...and set initial temperature parameter T.
    double temperature = initialTemperature;
    // Randomly assign documents to the k clusters.
    if (randomizeDocs) {
        collection.shuffle();
    }
    for (int i = 0; i < numDocs; i++) {
        int targetCluster = i % numClusters;
        clusters.get(targetCluster).addDocument(collection.getDocumentNameAt(i),
                collection.getDocument(collection.getDocumentNameAt(i)));
    }
    log.debug("..Initial clusters: " + clusters.toString());
    // 2) Repeat until temperature is reduced to the minimum.
    while (temperature > finalTemperature) {
        double previousAverageRadius = 0.0D;
        List<Cluster> prevClusters = new ArrayList<Cluster>();
        // 2.1) Run loop NUM_LOOP times.
        for (int loop = 0; loop < numberOfLoops; loop++) {
            // 2.1.1) Find a new set of clusters by altering the membership of some
            //        documents.
            // pick two clusters at random
            List<Integer> randomClusterIds = getRandomClusterIds(clusters);
            // pick two documents out of the clusters at random
            List<String> randomDocumentNames = getRandomDocumentNames(collection, randomClusterIds, clusters);
            // exchange the two random documents among the random clusters.
            clusters.get(randomClusterIds.get(0)).removeDocument(randomDocumentNames.get(0));
            clusters.get(randomClusterIds.get(0)).addDocument(randomDocumentNames.get(1),
                    collection.getDocument(randomDocumentNames.get(1)));
            clusters.get(randomClusterIds.get(1)).removeDocument(randomDocumentNames.get(1));
            clusters.get(randomClusterIds.get(1)).addDocument(randomDocumentNames.get(0),
                    collection.getDocument(randomDocumentNames.get(0)));
            // 2.1.2) Compare the difference between the values of the new and old
            //        set of clusters. If there is an improvement, accept the new 
            //        set of clusters, otherwise accept the new set of clusters with
            //        probability p.
            log.debug("..Intermediate clusters: " + clusters.toString());
            double averageRadius = getAverageRadius(clusters);
            if (averageRadius > previousAverageRadius) {
                // possible downhill move, calculate the probability of it being 
                // accepted
                double probability = Math.exp((previousAverageRadius - averageRadius) / temperature);
                if (probability < downhillProbabilityCutoff) {
                    // go back to the cluster before the changes
                    clusters.clear();
                    clusters.addAll(prevClusters);
                    continue;
                }
            }
            prevClusters.clear();
            prevClusters.addAll(clusters);
            previousAverageRadius = averageRadius;
        }
        // 2.2) Reduce the temperature based on the cooling schedule.
        temperature = temperature / 10;
    }
    // 3) Return the final set of clusters.
    return clusters;
}

From source file:org.ff4j.web.api.resources.domain.FF4jStatusApiBean.java

/**
 * Parameterized Constructor./*from  w  w w  .  j a  va2 s .  co  m*/
 *
 * @param ff4j
 *      target ff4j.
 */
public FF4jStatusApiBean(FF4j ff4j) {
    System.out.println("1");
    // UpTime
    long up = System.currentTimeMillis() - ff4j.getStartTime();
    long daynumber = new Double(Math.floor(up / (1000 * 3600 * 24))).longValue();
    up = up - (daynumber * 1000 * 3600 * 24);
    long hourNumber = new Double(Math.floor(up / (1000 * 3600))).longValue();
    up = up - (hourNumber * 1000 * 3600);
    long minutenumber = new Double(Math.floor(up / (1000 * 60))).longValue();
    up = up - (minutenumber * 1000 * 60);
    long secondnumber = new Double(Math.floor(up / 1000)).longValue();
    uptime = daynumber + " day(s) ";
    uptime += hourNumber + " hours(s) ";
    uptime += minutenumber + " minute(s) ";
    uptime += secondnumber + " seconds\"";
    autocreate = ff4j.isAutocreate();
    version = ff4j.getVersion();
    if (null != ff4j.getFeatureStore()) {
        featuresStore = new FeatureStoreApiBean(ff4j.getFeatureStore());
    }
    if (null != ff4j.getEventRepository()) {
        eventRepository = new EventRepositoryApiBean(ff4j.getEventRepository(), null, null);
    }
    if (null != ff4j.getAuthorizationsManager()) {
        authorizationsManager = new AuthorizationsManagerApiBean(ff4j.getAuthorizationsManager());
    }
}

From source file:com.alibaba.wasp.master.balancer.BaseLoadBalancer.java

protected boolean needsBalance(ClusterLoadState cs) {
    // Check if we even need to do any load balancing
    float average = cs.getLoadAverage(); // for logging
    // HBASE-3681 check sloppiness first
    int floor = (int) Math.floor(average * (1 - slop));
    int ceiling = (int) Math.ceil(average * (1 + slop));

    return cs.getMinLoad() > ceiling || cs.getMaxLoad() < floor;
}