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:com.sunchenbin.store.feilong.core.util.RandomUtil.java

/**
 * 0-?.//from  ww w.  j  av  a 2 s . com
 * 
 * <p>
 * ??{@link #JVM_RANDOM}
 * </p>
 * 
 * @param number
 *            ?
 * @return 0-?
 * @see java.lang.Math#random()
 */
public static long createRandom(Number number) {
    double random = JVM_RANDOM.nextDouble();
    return (long) Math.floor(random * number.longValue());
}

From source file:com.almende.test.dht.TestScale.java

/**
 * Test a large nof nodes.//from  www  .  j  a  v  a  2 s . c o m
 * 
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws URISyntaxException
 *             the URI syntax exception
 * @throws InterruptedException
 *             the interrupted exception
 */
@Test
public void testScale() throws IOException, URISyntaxException, InterruptedException {
    DHTAgent[] agents = new DHTAgent[NOFNODES];

    DHTAgent agent = new DHTAgent("agent_0");
    agents[0] = agent;
    for (int i = 1; i < NOFNODES; i++) {
        System.out.print("Created node:agent_" + i + "\r");
        DHTAgent next = new DHTAgent("agent_" + i);
        try {
            next.getDht().join(agent.asNode());
        } catch (NullPointerException e) {
            System.err.println("NPE at:" + i);
            throw e;
        }
        agent = next;
        agents[i] = agent;
    }
    final Key key = Key.fromString("Hello world");
    final ObjectNode value = JOM.createObjectNode();
    value.put("Hello:", "world!");
    agents[0].getDht().iterative_store_value(key, value);

    JsonNode result = agents[(int) Math.floor(Math.random() * NOFNODES)].getDht()
            .iterative_find_value(Key.fromString("Hello world"), false);

    assertEquals(result, value);

    final int otherIdx = (int) Math.floor(Math.random() * NOFNODES);
    JsonNode result2 = agents[otherIdx].getDht().iterative_find_value(Key.fromString("Hello world"), false);
    assertEquals(result2, value);

    final Key key2 = Key.fromString("Some other key");
    final ObjectNode value2 = JOM.createObjectNode();
    value2.put("Hello:", "world2!");
    agents[0].getDht().iterative_store_value(key2, value2);

    JsonNode result3 = agents[(int) Math.floor(Math.random() * NOFNODES)].getDht()
            .iterative_find_value(Key.fromString("Some other key"), false);

    assertEquals(result3, value2);

    JsonNode result4 = agents[otherIdx].getDht().iterative_find_value(Key.fromString("Hello world"), false);
    assertNotSame(result4, value2);
    assertEquals(result4, value);

    JsonNode result5 = agents[otherIdx].getDht().iterative_find_value(Key.fromString("Hello world"), false);
    assertEquals(result5, value);
    JsonNode result6 = agents[otherIdx].getDht().iterative_find_value(Key.fromString("Hello world!"), false);
    assertNotSame(result6, value);
    assertEquals(result6, JOM.createNullNode());

    final BitSet set = key2.getVal();
    set.set(10, !set.get(10));
    final Key key3 = new Key(set);
    final ObjectNode value3 = JOM.createObjectNode();
    value3.put("Hello:", "world3!");
    agents[0].getDht().iterative_store_value(key3, value3);

    JsonNode result7 = agents[otherIdx + 2].getDht().iterative_find_value(key3, false);
    assertEquals(result7, value3);

    int count = 0;
    for (final DHTAgent a : agents) {
        if (a.getDht().hasValues()) {
            count++;
        }
    }
    System.out.println(count + " agents have some value stored.");
}

From source file:org.bitcoinrt.client.StubMtgoxClient.java

@Override
public void start() {

    this.executor = Executors.newSingleThreadExecutor();

    this.executor.submit(new Runnable() {
        @Override//from   w w  w  .j a v a 2s .c o  m
        public void run() {
            while (!shuttingDown) {

                String expression = "{\"channel\":\"dbf1dee9-4f2e-4a08-8cb7-748919a71b21\",\"op\":\"private\","
                        + "\"origin\":\"broadcast\",\"private\":\"trade\",\"trade\":{\"amount\":[%f],"
                        + "\"date\":[%d],\"price\":12.239,\"exchange\":\"mtgoxUSD\","
                        + "\"price_currency\":\"USD\",\"primary\":\"Y\","
                        + "\"txid\":\"1348679989121772\",\"type\":\"trade\"}}";

                long timestamp = (long) (Math.floor(new Date().getTime() / 1000));
                double amount = Math.floor(Math.random() * 20);
                String message = String.format(expression, amount, timestamp);
                onMessage(message);

                try {
                    Thread.sleep(7000);
                } catch (InterruptedException ex) {
                    logger.debug("Stub MtGox service interrupted");
                }
            }
            logger.debug("Stub MtGox service stopped");
        }
    });

}

From source file:Engine.WorldMap.java

public static double DoubleModulo(double a, double b) {
    return (a - Math.floor(a / b) * b);
}

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

/**
 * Cluster.//  ww  w.  j a  v a  2  s  .c o  m
 *
 * @param collection the collection
 * @return the list
 */
public List<Cluster> cluster(DocumentCollection collection) {
    int numDocs = collection.size();
    int numClusters = 0;
    if (initialClusterAssignments == null) {
        // compute initial cluster assignments
        IdGenerator idGenerator = new IdGenerator(numDocs);
        numClusters = (int) Math.floor(Math.sqrt(numDocs));
        initialClusterAssignments = new String[numClusters];
        for (int i = 0; i < numClusters; i++) {
            int docId = idGenerator.getNextId();
            initialClusterAssignments[i] = collection.getDocumentNameAt(docId);
        }
    } else {
        numClusters = initialClusterAssignments.length;
    }

    // build initial clusters
    List<Cluster> clusters = new ArrayList<Cluster>();
    for (int i = 0; i < numClusters; i++) {
        Cluster cluster = new Cluster("C" + i);
        cluster.addDocument(initialClusterAssignments[i], collection.getDocument(initialClusterAssignments[i]));
        clusters.add(cluster);
    }
    log.debug("..Initial clusters:" + clusters.toString());

    List<Cluster> prevClusters = new ArrayList<Cluster>();

    // Repeat until termination conditions are satisfied
    for (;;) {
        // For every cluster i, (re-)compute the centroid based on the
        // current member documents. (We have moved 2.2 above 2.1 because
        // this needs to be done before every iteration).
        RealMatrix[] centroids = new RealMatrix[numClusters];
        for (int i = 0; i < numClusters; i++) {
            RealMatrix centroid = clusters.get(i).getCentroid();
            centroids[i] = centroid;
        }
        // For every document d, find the cluster i whose centroid is 
        // most similar, assign d to cluster i. (If a document is 
        // equally similar from all centroids, then just dump it into 
        // cluster 0).
        for (int i = 0; i < numDocs; i++) {
            int bestCluster = 0;
            double maxSimilarity = Double.MIN_VALUE;
            RealMatrix document = collection.getDocumentAt(i);
            String docName = collection.getDocumentNameAt(i);
            for (int j = 0; j < numClusters; j++) {
                double similarity = clusters.get(j).getSimilarity(document);
                if (similarity > maxSimilarity) {
                    bestCluster = j;
                    maxSimilarity = similarity;
                }
            }
            for (Cluster cluster : clusters) {
                if (cluster.getDocument(docName) != null) {
                    cluster.removeDocument(docName);
                }
            }
            clusters.get(bestCluster).addDocument(docName, document);
        }
        log.debug("..Intermediate clusters: " + clusters.toString());

        // Check for termination -- minimal or no change to the assignment
        // of documents to clusters.
        if (CollectionUtils.isEqualCollection(clusters, prevClusters)) {
            break;
        }
        prevClusters.clear();
        prevClusters.addAll(clusters);
    }
    // Return list of clusters
    log.debug("..Final clusters: " + clusters.toString());
    return clusters;
}

From source file:javatranslation.matlab.dfa.java

public static void dfafunction(double[] tau, double MinBox, double MaxBox, int DFAorder) {

    double[] incoef = null;
    double[] l = null;
    l = new double[50];
    incoef = new double[50];
    for (int i = 0; i < 50; i++) {
        l = logspace(MinBox, MaxBox);// w ww .  j  av a  2 s  .com
        //System.out.println(l[i]);
        incoef[i] = Math.round(l[i]);
    }
    double xx = mean(tau);
    for (int i = 0; i < tau.length; i++) {
        tau[i] = tau[i] - xx;
    }
    double[] Y = cumsum(tau, dfa.mean(tau));
    double maxnumseg = incoef.length;
    double[] winlen = null;
    winlen = new double[50];
    for (int truta = 0; truta < 50; truta++) {
        winlen[truta] = incoef[truta];
    }
    Arrays.sort(winlen);
    ArrayUtils.reverse(winlen);

    double Ylength = Y.length;
    double F[][] = new double[(int) maxnumseg][1];
    for (int k = 0; k < maxnumseg; k++) {
        F[k][0] = 0;
    }
    double[] timevec = new double[50];
    for (int kk = 0; kk < maxnumseg; kk++) {
        timevec[kk] = winlen[kk];
        double numsegm = Math.floor(Ylength / winlen[kk]);
        double tempY[][] = new double[1][(int) numsegm];
        for (int k = 0; k < numsegm; k++) {
            tempY[0][k] = 0;
        }
        for (int zz = 0; zz < numsegm; zz++) {
            double overflowtest = zz * winlen[kk];
            if (overflowtest <= Ylength) {
                double[] tempvec = null;
                int ko = 0;
                for (double p = ((zz - 1) * winlen[kk] + 1); p <= (zz
                        * winlen[kk]); p = ((zz - 1) * winlen[kk] + 1) + 1) { // there are some errors in this loop
                    tempvec[ko] = Y[(int) p];
                    System.out.println(tempvec[(int) p]);
                    ko++;
                }
                //double temppol = polyfit(timevec,tempvec,DFAorder);
                MultivariateVectorOptimizer optimizer;
                optimizer = null;
                PolynomialFitter x = new PolynomialFitter(optimizer); // error here too
                double[] temppol = x.fit(DFAorder, timevec);

                double[] temppol2 = x.fit(DFAorder, tempvec);
                double[] arrayOfCoefficients = new double[temppol2.length];
                arrayOfCoefficients = temppol2;
                int len = arrayOfCoefficients.length;
                double retAnswer = 0;
                double ret = 0;
                for (int i = 0; i < len; i++) {
                    retAnswer = retAnswer + Math.pow(arrayOfCoefficients[i], i);
                }
                for (int i = 0; i < tempvec.length; i++) {
                    ret = tempvec[i] - (Math.pow(retAnswer, 2));
                }
                tempY[0][zz] = ((ret) / winlen[kk]);
            }
        }
        int k;
        double[] kopp = new double[(int) maxnumseg];
        for (k = 0; k < maxnumseg; k++) {
            kopp[k] = tempY[0][k];
        }
        double nonzerotempY = dfa.sum2(kopp);
        F[kk][0] = Math.sqrt(dfa.sum(kopp) / nonzerotempY);

    }
    double[] LF;
    LF = new double[(int) maxnumseg];
    double[] LN;
    LN = new double[(int) maxnumseg];
    for (int i = 0; i < maxnumseg; i++) {
        LF[i] = Math.log10(F[i][0]);
        LN[i] = Math.log10(winlen[i]);
    }
    double[][] XLN = new double[LN.length][LN.length];
    for (int i = 0; i < LN.length; i++) {
        XLN[i][0] = 1;
        XLN[i][1] = LN[i];
    }
    SimpleRegression x;
    x = new SimpleRegression();
    x.addObservations(XLN, LF); // and probably error in this one too
    RegressionResults b = x.regress();
    // System.out.println(b.getParameterEstimates());

    //double LF=Math.log10(F); % log fluctuations
    //double LN=Math.log10(winlen);
}

From source file:com.ables.pix.utility.PictureOps.java

public static BufferedImage tilt(BufferedImage image, double rotation) {
    double sin = Math.abs(Math.sin(getAngle()));
    double cos = Math.abs(Math.cos(getAngle()));
    int w = image.getWidth(), h = image.getHeight();

    int neww = (int) Math.floor(w * cos + sin * h), newh = (int) Math.floor(h * cos + sin * w);
    GraphicsConfiguration gc = getDefaultConfiguration();
    BufferedImage rotated = gc.createCompatibleImage(neww, newh);
    Graphics2D g = rotated.createGraphics();
    g.translate((neww - w) / 2, (newh - h / 2));
    g.rotate(getAngle(), w / 2, h / 2);//from   w  w  w  .j  a va 2  s.c  om
    g.drawRenderedImage(image, null);
    g.dispose();
    return rotated;
}

From source file:es.udc.gii.common.eaf.algorithm.operator.selection.UniformSelection.java

@Override
protected Individual select(EvolutionaryAlgorithm algorithm, List<Individual> individuals) {

    int randomPos;

    randomPos = (int) Math.floor(EAFRandom.nextDouble() * individuals.size());

    return individuals.get(randomPos);

}

From source file:com.itemanalysis.psychometrics.scaling.PercentileRank.java

/**
 * All doubles are converted to integers see page 44, Kolen and Brennan(2004).
 *
 * @param score a test score.//from  w  ww.  j a  va2  s  .  c  om
 */
public void addValue(Double score) {
    int iScore = Double.valueOf(Math.floor(score + 0.5)).intValue();
    if (iScore >= min && iScore <= max) {
        freqTable.addValue(iScore);
    }
}

From source file:com.ai.bss.webui.datainit.DataController.java

@RequestMapping(value = "/collection/{id}", method = RequestMethod.GET)
public String collection(@PathVariable("id") String collectionName,
        @RequestParam(value = "page", defaultValue = "1") int pageNumber,
        @RequestParam(value = "itemsperpage", defaultValue = "5") int itemsPerPage, Model model) {
    DataResults dataResults = dbInit.obtainCollection(collectionName, itemsPerPage,
            (pageNumber - 1) * itemsPerPage + 1);

    model.addAttribute("items", dataResults.getItems());

    int totalItems = dataResults.getTotalItems();
    int numPages = ((int) Math.floor(totalItems / itemsPerPage)) + 1;
    model.addAttribute("numPages", numPages);
    model.addAttribute("page", pageNumber);
    model.addAttribute("itemsPerPage", itemsPerPage);
    model.addAttribute("collectionName", collectionName);
    return "data/collection";
}