Example usage for java.lang Math rint

List of usage examples for java.lang Math rint

Introduction

In this page you can find the example usage for java.lang Math rint.

Prototype

public static double rint(double a) 

Source Link

Document

Returns the double value that is closest in value to the argument and is equal to a mathematical integer.

Usage

From source file:com.mapr.synth.TermGeneratorTest.java

@Test
public void speciesCounts() {
    final boolean transpose = false;

    // generate an example of species sampled on multiple days
    LongTail<Integer> terms = new LongTail<Integer>(0.5, 0.3) {
        int max = 0;

        @Override// ww  w. j a va 2  s. com
        protected Integer createThing() {
            return ++max;
        }
    };

    // I picked seeds to get a good illustration ... want a reasonable number of species and surprises
    terms.setSeed(2);

    Random gen = new Random(1);
    SortedSet<Integer> vocabulary = Sets.newTreeSet();
    List<Multiset<Integer>> r = Lists.newArrayList();

    for (int i = 0; i < 2000; i++) {
        double length = Math.rint(gen.nextGaussian() * 10 + 50);
        Multiset<Integer> counts = HashMultiset.create();
        for (int j = 0; j < length; j++) {
            counts.add(terms.sample());
        }
        r.add(counts);
    }

    if (transpose) {
        for (Multiset<Integer> day : r) {
            vocabulary.addAll(day.elementSet());
        }

        System.out.printf("%d\n", vocabulary.size());
        for (Integer s : vocabulary) {
            String sep = "";
            for (Multiset<Integer> day : r) {
                System.out.printf("%s%s", sep, day.count(s));
                sep = "\t";
            }
            System.out.printf("\n");
        }
    } else {
        System.out.printf("%d\n", vocabulary.size());
        for (Multiset<Integer> day : r) {
            vocabulary.addAll(day.elementSet());
            String sep = "";
            System.out.printf("%s%s", sep, vocabulary.size());
            sep = "\t";
            for (Integer s : vocabulary) {
                System.out.printf("%s%s", sep, day.count(s));
                sep = "\t";
            }
            System.out.printf("\n");
        }

        Multiset<Integer> total = HashMultiset.create();
        for (Multiset<Integer> day : r) {
            for (Integer species : day.elementSet()) {
                total.add(species, day.count(species));
            }
        }
        String sep = "";
        System.out.printf("%s%s", sep, total.elementSet().size());
        sep = "\t";
        for (Integer s : vocabulary) {
            System.out.printf("%s%s", sep, total.count(s));
            sep = "\t";
        }
        System.out.printf("\n");
    }
}

From source file:com.screenslicer.core.scrape.ProcessPage.java

private static List<Result> finalizeResults(Results results, String currentUrl, Element body, int page,
        String query, Leniency leniency, boolean trim, Map<String, Object> cache) {
    if (WebApp.DEBUG) {
        System.out.println("Returning: (leniency) " + leniency.name());
    }//  ww  w  .j ava2s . c  o  m
    if (trim && !results.results().isEmpty()) {
        Results untrimmed = perform(body, page, query, leniency, false, cache);
        int trimmedScore = results.fieldScore(true, false);
        int untrimmedScore = untrimmed.fieldScore(true, false);
        if (untrimmedScore > (int) Math.rint(((double) trimmedScore) * 1.05d)) {
            if (WebApp.DEBUG) {
                System.out.println("Un-trimmed selected.");
            }
            return Util.fixUrls(untrimmed.results(), currentUrl);
        }
    }
    if (WebApp.DEBUG) {
        System.out.println("Trimmed selected.");
    }
    return Util.fixUrls(results.results(), currentUrl);
}

From source file:sadl.models.pdrta.PDRTAInput.java

private void calcHistBorders(TIntList timePoints, int numHistoBins) {

    timePoints.sort();/*from  ww w .ja v a2  s.  c o m*/
    histoBorders = new int[numHistoBins - 1];
    for (int i = 1; i < numHistoBins; i++) {
        final double idx = ((double) i / (double) numHistoBins) * (timePoints.size() - 1);
        final double idxFloor = Math.floor(idx);
        if (Precision.equals(idx, idxFloor)) {
            histoBorders[i - 1] = timePoints.get((int) idx);
        } else {
            final double vFloor = timePoints.get((int) idxFloor);
            final double vCeil = timePoints.get((int) (idxFloor + 1.0));
            final double val = (vFloor * (1.0 - (idx - idxFloor))) + (vCeil * (idx - idxFloor));
            histoBorders[i - 1] = (int) Math.rint(val);
        }
    }
}

From source file:com.ajncespedes.puntogpsqr.MapsActivity.java

/**
 * Mtodo que detecta cambios en nuestra posicin actual y enva notificaciones que recibe android wear para obtener la distancia
 * hasta el objetivo y para avisarnos si hemos llegado.
 *///from  ww  w.  j ava  2  s  . co m
@Override
public void onMyLocationChange(Location loc) {

    //Obtenemos la distancia desde nuestra posicin hasta el objetivo
    double distancia = Math.rint(loc.distanceTo(destino) * 10) / 10;

    //Mandamos el aviso de la distancia cada 10 metros
    if (distancia > 5 && distancia % 10 < 1) {
        String aviso = "Distancia " + distancia + " m";
        Notification notificacion = new NotificationCompat.Builder(getApplication())
                .setSmallIcon(R.mipmap.ic_launcher).setContentTitle("Aviso de Distancia").setContentText(aviso)
                .extend(new NotificationCompat.WearableExtender().setHintShowBackgroundOnly(true))
                .setVibrate(new long[] { 0, 500 }).setSubText("Distancia hasta el objetivo").build();
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplication());
        int notificacionId = 1;
        notificationManager.notify(notificacionId, notificacion);
    } else if (distancia < 5) { //Si la distancia es menor que 5, consideramos que ya hemos llegado
        if (!llegada) {
            String aviso = "Ya hemos llegado al destino!";
            Notification notificacion = new NotificationCompat.Builder(getApplication())
                    .setSmallIcon(R.mipmap.ic_launcher).setContentTitle("Aviso de llegada")
                    .setContentText(aviso)
                    .extend(new NotificationCompat.WearableExtender().setHintShowBackgroundOnly(true))
                    .setVibrate(new long[] { 0, 1000, 1000 }).setSubText("Distancia hasta el objetivo").build();
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplication());
            int notificacionId = 1;
            notificationManager.notify(notificacionId, notificacion);
            llegada = true;
        }
    }
}

From source file:io.cortical.retina.core.ExpressionsTest.java

/**
 * {@link Expressions#getFingerprintForExpression(io.cortical.retina.model.Model, double)}
 * @throws JsonProcessingException      should never be thrown
 * @throws ApiException     should never be thrown
 *//*from   w  w w .j a v a 2  s .  c  o  m*/
@Test
public void testGetFingerprintForExpression() throws ApiException, JsonProcessingException {
    double sparsity = 0.02;

    when(expressionsApi.resolveExpression(eq(TERM_1_JSON), eq(NOT_NULL_RETINA), eq(0.02)))
            .thenReturn(createFingerprint(sparsity));
    Fingerprint fingerprint = expressions.getFingerprintForExpression(TERM_1, sparsity);
    assertEquals(
            "[124, 133, 146, 181, 192, 230, 249, 279, 442, 447, 514, 597, 612, "
                    + "659, 785, 858, 861, 895, 1150, 1247, 1262, 1315, 1321, 1485, "
                    + "1496, 1518, 1522, 1535, 1580, 1685, 1701, 1882, 1896, 2054, "
                    + "2068, 2097, 2108, 2115, 2231, 2235, 2290, 2404, 2405, 2432, "
                    + "2466, 2474, 2489, 2502, 2520, 2534, 2599, 2623, 2799, 2800, "
                    + "2821, 2838, 2906, 2937, 2963, 3033, 3092, 3210, 3213, 3261, "
                    + "3286, 3401, 3436, 3596, 3987, 4106, 4123, 4160, 4229, 4263, "
                    + "4352, 4492, 4517, 4539, 4546, 4568, 4596, 4623, 4651, 4666, "
                    + "4752, 4763, 4777, 4778, 4871, 4965, 5006, 5058, 5090, 5163, "
                    + "5166, 5186, 5383, 5444, 5513, 5542, 5566, 5627, 5635, 5649, "
                    + "5864, 5902, 5904, 5922, 5982, 6005, 6042, 6047, 6078, 6124, "
                    + "6133, 6161, 6200, 6252, 6268, 6290, 6301, 6333, 6353, 6429, "
                    + "6467, 6484, 6496, 6513, 6586, 6635, 6843, 6862, 6897, 6933, "
                    + "6938, 6955, 7066, 7090, 7121, 7126, 7148, 7151, 7205, 7236, "
                    + "7253, 7302, 7393, 7492, 7501, 7516, 7526, 7541, 7592, 7596, "
                    + "7678, 7684, 7729, 7744, 7869, 7873, 7886, 7927, 7972, 7998, "
                    + "8148, 8274, 8332, 8335, 8505, 8514, 8544, 8732, 8756, 8758, "
                    + "8845, 8894, 8981, 8983, 8993, 8994, 9115, 9172, 9355, 9365, "
                    + "9396, 9503, 9559, 9624, 9642, 9676, 9737, 9762, 9791, 9811, "
                    + "9877, 10061, 10078, 10096, 10264, 10288, 10313, 10338, 10344, "
                    + "10368, 10405, 10430, 10495, 10527, 10545, 10587, 10629, 10732, "
                    + "10766, 10782, 10800, 10822, 10830, 10904, 10986, 11193, 11235, "
                    + "11276, 11286, 11311, 11371, 11402, 11421, 11423, 11466, 11502, "
                    + "11570, 11595, 11688, 11798, 11885, 11896, 11920, 11953, 12091, "
                    + "12208, 12218, 12286, 12308, 12329, 12342, 12413, 12419, 12472, "
                    + "12486, 12530, 12608, 12623, 12633, 12699, 12704, 12792, 12827, "
                    + "12920, 12954, 13023, 13040, 13042, 13079, 13084, 13108, 13140, "
                    + "13195, 13201, 13256, 13264, 13391, 13398, 13442, 13463, 13487, "
                    + "13532, 13554, 13584, 13659, 13662, 13683, 13884, 13931, 14014, "
                    + "14018, 14136, 14183, 14194, 14283, 14310, 14515, 14559, 14603, "
                    + "14647, 14666, 14706, 14722, 14732, 14800, 14804, 14819, 14820, "
                    + "14886, 14953, 15062, 15081, 15247, 15380, 15403, 15434, 15471, "
                    + "15562, 15580, 15765, 15769, 15835, 15851, 15878, 15889, 15958, "
                    + "15991, 16016, 16032, 16137, 16143, 16318, 16354, 16366]",
            Arrays.toString(fingerprint.getPositions()));
    assertEquals(Math.rint(16384. * 0.02), fingerprint.getPositions().length, 0.001);
    verify(expressionsApi, times(1)).resolveExpression(eq(TERM_1_JSON), eq(NOT_NULL_RETINA), eq(sparsity));
}

From source file:org.jtrfp.trcl.TriangleList.java

private void setupVertex(int vIndex, int gpuTVIndex, int triangleIndex, TextureDescription td)
        throws ExecutionException, InterruptedException {
    final int numFrames = getPrimitives().length;
    final Triangle t = triangleAt(0, triangleIndex);
    final Vector3D pos = t.getVertices()[vIndex].getPosition();
    final TriangleVertexWindow vw = (TriangleVertexWindow) getMemoryWindow();
    ////////////////////// V E R T E X //////////////////////////////
    if (numFrames == 1) {
        vw.x.set(gpuTVIndex, (short) applyScale(pos.getX()));
        vw.y.set(gpuTVIndex, (short) applyScale(pos.getY()));
        vw.z.set(gpuTVIndex, (short) applyScale(pos.getZ()));
        final Vector3D normal = t.getVertices()[vIndex].getNormal();
        vw.normX.set(gpuTVIndex, (byte) (normal.getX() * 127));
        vw.normY.set(gpuTVIndex, (byte) (normal.getY() * 127));
        vw.normZ.set(gpuTVIndex, (byte) (normal.getZ() * 127));
    } else {// w ww  .ja va  2  s . c  om
        float[] xFrames = new float[numFrames];
        float[] yFrames = new float[numFrames];
        float[] zFrames = new float[numFrames];
        float[] nxFrames = new float[numFrames];
        float[] nyFrames = new float[numFrames];
        float[] nzFrames = new float[numFrames];
        for (int i = 0; i < numFrames; i++) {
            xFrames[i] = (float) applyScale(
                    triangleAt(i, triangleIndex).getVertices()[vIndex].getPosition().getX());
        }
        xyzAnimator.addFrames(xFrames);

        for (int i = 0; i < numFrames; i++) {
            yFrames[i] = (float) applyScale(
                    triangleAt(i, triangleIndex).getVertices()[vIndex].getPosition().getY());
        }
        xyzAnimator.addFrames(yFrames);

        for (int i = 0; i < numFrames; i++) {
            zFrames[i] = (float) applyScale(
                    triangleAt(i, triangleIndex).getVertices()[vIndex].getPosition().getZ());
        }
        xyzAnimator.addFrames(zFrames);

        for (int i = 0; i < numFrames; i++) {
            nxFrames[i] = (float) Math
                    .rint(triangleAt(i, triangleIndex).getVertices()[vIndex].getNormal().getX() * 127);
        }
        xyzAnimator.addFrames(nxFrames);

        for (int i = 0; i < numFrames; i++) {
            nyFrames[i] = (float) Math
                    .rint(triangleAt(i, triangleIndex).getVertices()[vIndex].getNormal().getY() * 127);
        }
        xyzAnimator.addFrames(nyFrames);

        for (int i = 0; i < numFrames; i++) {
            nzFrames[i] = (float) Math
                    .rint(triangleAt(i, triangleIndex).getVertices()[vIndex].getNormal().getZ() * 127);
        }
        xyzAnimator.addFrames(nzFrames);
    } //end else(frames!=1)
      //////////////// T E X T U R E ///////////////////////////
    if (td == null) {
        System.err.println("Stack trace of triangle creation below. NullPointerException follows.");
        for (StackTraceElement el : t.getCreationStackTrace()) {
            System.err.println("\tat " + el.getClassName() + "." + el.getMethodName() + "(" + el.getFileName()
                    + ":" + el.getLineNumber() + ")");
        } //end for(stackTrace)
        throw new NullPointerException("Texture for triangle in " + debugName + " intolerably null.");
    }
    if (td instanceof Texture) {// Static texture
        final int sideScalar = ((Texture) td).getSideLength() - 1;
        if (animateUV && numFrames > 1) {// Animated UV
            float[] uFrames = new float[numFrames];
            float[] vFrames = new float[numFrames];
            final WindowAnimator uvAnimator = new WindowAnimator(getFlatTVWindow(), 2, // UV per vertex
                    numFrames, false, getVertexSequencer(timeBetweenFramesMsec, numFrames),
                    new UVXferFunc(gpuTVIndex * UVXferFunc.BACK_STRIDE_LEN));
            getModel().addTickableAnimator(uvAnimator);
            uvAnimator.setDebugName(debugName + ".uvAnimator");
            for (int i = 0; i < numFrames; i++) {
                uFrames[i] = (float) Math.rint(sideScalar * triangleAt(i, triangleIndex).getUV(vIndex).getX());
                vFrames[i] = (float) Math
                        .rint(sideScalar * (1 - triangleAt(i, triangleIndex).getUV(vIndex).getY()));
            } // end for(numFrames)
            uvAnimator.addFrames(uFrames);
            uvAnimator.addFrames(vFrames);
        } else {// end if(animateUV)
            vw.u.set(gpuTVIndex, (short) Math.rint(sideScalar * t.getUV(vIndex).getX()));
            vw.v.set(gpuTVIndex, (short) Math.rint(sideScalar * (1 - t.getUV(vIndex).getY())));
        } // end if(!animateUV)
        final int textureID = ((Texture) td).getTexturePage();
        vw.textureIDLo.set(gpuTVIndex, (byte) (textureID & 0xFF));
        vw.textureIDMid.set(gpuTVIndex, (byte) ((textureID >> 8) & 0xFF));
        vw.textureIDHi.set(gpuTVIndex, (byte) ((textureID >> 16) & 0xFF));
    } // end if(Texture)
    if (td instanceof AnimatedTexture) {//Animated texture
        final AnimatedTexture at = (AnimatedTexture) td;
        if (animateUV && numFrames > 1) {// Animated UV
            float[] uFrames = new float[numFrames];
            float[] vFrames = new float[numFrames];
            final WindowAnimator uvAnimator = new WindowAnimator(getFlatTVWindow(), 2, // UV per vertex
                    numFrames, false, getVertexSequencer(timeBetweenFramesMsec, numFrames),
                    new UVXferFunc(gpuTVIndex * UVXferFunc.BACK_STRIDE_LEN));
            getModel().addTickableAnimator(uvAnimator);
            for (int i = 0; i < numFrames; i++) {
                final int sideScalar = at.getFrames()[i].getSideLength() - 1;
                uFrames[i] = (float) Math.rint(sideScalar * triangleAt(i, triangleIndex).getUV(vIndex).getX());
                vFrames[i] = (float) Math
                        .rint(sideScalar * (1 - triangleAt(i, triangleIndex).getUV(vIndex).getY()));
            } // end for(numFrames)
            uvAnimator.addFrames(uFrames);
            uvAnimator.addFrames(vFrames);
        } else {// end if(animateUV)
            final int sideScalar = at.getFrames()[0].getSideLength() - 1;
            vw.u.set(gpuTVIndex, (short) Math.rint(sideScalar * t.getUV(vIndex).getX()));
            vw.v.set(gpuTVIndex, (short) Math.rint(sideScalar * (1 - t.getUV(vIndex).getY())));
        } // end if(!animateUV)
        final TexturePageAnimator texturePageAnimator = new TexturePageAnimator(at, vw, gpuTVIndex);
        texturePageAnimator.setDebugName(debugName + ".texturePageAnimator");
        getModel().addTickableAnimator(texturePageAnimator);
    } //end if(animated texture)
}

From source file:us.mn.state.health.lims.analyzerimport.analyzerreaders.CobasC311Reader.java

private String adjustResult(String analyzerTestName, String result) {

    if (ALTL_NAME.equals(analyzerTestName)) {
        return String.valueOf(Math.rint(Double.parseDouble(result) + ROUND_UP_KICKER)).split("\\.")[0];
    }//from ww  w.j av  a 2  s .  c o  m

    if (ASTL_NAME.equals(analyzerTestName)) {
        return String.valueOf(Math.rint(Double.parseDouble(result) + ROUND_UP_KICKER)).split("\\.")[0];
    }

    if (CREATININ_NAME.equals(analyzerTestName)) {
        return String.valueOf(Math.rint((Double.parseDouble(result) + ROUND_UP_KICKER) * 10.0)).split("\\.")[0];
    }

    if (GLYCEMIA_NAME.equals(analyzerTestName)) {
        return String.valueOf(Math.rint((Double.parseDouble(result) + ROUND_UP_KICKER) * 100) / 100);
    }

    return result;
}

From source file:us.mn.state.health.lims.analyzerimport.analyzerreaders.FACSCantoReader.java

private String roundTwoDigits(String result) {

    try {/* ww  w  .  ja  va2 s  . com*/
        Double doubleResult = Double.parseDouble(result);
        StringBuilder sb = new StringBuilder();
        Formatter formatter = new Formatter(sb);
        formatter.format("%.2f", (Math.rint(doubleResult * 100.0) / 100.0));
        return sb.toString();
    } catch (NumberFormatException e) {
        return result;
    }
}

From source file:projects.upc.exec.HrDiagram.java

/**
 * Main constructor./*  w ww  . ja va 2 s . c o  m*/
 */
public HrDiagram() {

    List<UpcStar> upcStars = UpcUtils.loadUpcCatalogue();
    List<UpcStar> hipStars = UpcUtils.getHipparcosSubset(upcStars);
    List<UpcStar> unmatchedStars = UpcUtils.getUnmatchedSubset(upcStars);

    upcStarCrossMatches = XmUtil.getUpcStarCrossMatchMap(upcStars);
    hipStarCrossMatches = XmUtil.getUpcStarCrossMatchMap(hipStars);
    unmatchedStarCrossMatches = XmUtil.getUpcStarCrossMatchMap(unmatchedStars);

    logger.info("Loaded " + upcStarCrossMatches.size() + " UpcStars with SSA cross matches");
    logger.info("Loaded " + hipStarCrossMatches.size() + " UpcStars with Hipparcos and SSA cross matches");
    logger.info("Loaded " + unmatchedStarCrossMatches.size()
            + " UpcStars with no parallax cross-match, and with SSA cross matches");

    starsToPlot = upcStarCrossMatches;

    useHip = false;
    method = METHOD.NAIVE;
    fMax = 1.0;

    final JCheckBox plotAllCheckBox = new JCheckBox("Plot all UPC stars: ", true);
    plotAllCheckBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (plotAllCheckBox.isSelected()) {
                starsToPlot = upcStarCrossMatches;
                updateChart();
            }
        }
    });

    final JCheckBox plotHipCheckBox = new JCheckBox("Plot Hipparcos stars only: ", false);
    plotHipCheckBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (plotHipCheckBox.isSelected()) {
                starsToPlot = hipStarCrossMatches;
                updateChart();
            }
        }
    });

    final JCheckBox plotUnmatchedCheckBox = new JCheckBox("Plot all stars with no external match: ", false);
    plotUnmatchedCheckBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (plotUnmatchedCheckBox.isSelected()) {
                starsToPlot = unmatchedStarCrossMatches;
                updateChart();
            }
        }
    });

    final ButtonGroup bg = new ButtonGroup();
    bg.add(plotHipCheckBox);
    bg.add(plotAllCheckBox);
    bg.add(plotUnmatchedCheckBox);

    JCheckBox useHipCheckBox = new JCheckBox("Use Hipparcos parallaxes when available", useHip);
    useHipCheckBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            useHip = !useHip;
            updateChart();
        }
    });

    final JComboBox<METHOD> methodComboBox = new JComboBox<METHOD>(METHOD.values());
    methodComboBox.setSelectedItem(method);
    methodComboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            method = (METHOD) methodComboBox.getSelectedItem();
            updateChart();
        }
    });

    final JSlider fSlider = GuiUtil.buildSlider(0.0, 2.0, 5, "%3.3f");
    fSlider.setValue((int) Math.rint(100.0 * fMax));
    final JLabel fLabel = new JLabel(getFLabel());
    // Create a change listener fot these
    ChangeListener cl = new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            JSlider source = (JSlider) e.getSource();

            if (source == fSlider) {
                // Compute fractional parallax error from slider position
                double newF = (2.0 * source.getValue() / 100.0);
                fMax = newF;
                fLabel.setText(getFLabel());
            }
            updateChart();
        }
    };
    fSlider.addChangeListener(cl);
    // Add a bit of padding to space things out
    fSlider.setBorder(new EmptyBorder(5, 5, 5, 5));

    // Present controls below the HR diagram
    JPanel controls = new JPanel(new GridLayout(3, 3));
    controls.add(plotAllCheckBox);
    controls.add(plotHipCheckBox);
    controls.add(plotUnmatchedCheckBox);
    controls.add(new JLabel("Distance estimation method:"));
    controls.add(methodComboBox);
    controls.add(useHipCheckBox);
    controls.add(fLabel);
    controls.add(fSlider);

    // Initialise the ChartPanel
    updateChart();

    // Build the panel contents
    setLayout(new BorderLayout());
    add(chartPanel, BorderLayout.CENTER);
    add(controls, BorderLayout.SOUTH);
}

From source file:org.esa.beam.util.math.FastMathTest.java

@Test
public void testMathRint() {
    for (double i = 0; i < numItr; ++i) {
        double val = Math.rint(i);
    }//from  w  w w .ja v  a2  s. co  m
}