Example usage for java.lang Math ceil

List of usage examples for java.lang Math ceil

Introduction

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

Prototype

public static double ceil(double a) 

Source Link

Document

Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.

Usage

From source file:info.raack.appliancelabeler.machinelearning.appliancedetection.algorithmcomponents.frequencyanalysis.JTransformsFrequencyAnalyzer.java

@Override
public double[] retrieveMostPromimentWavelengthBoxAmplitudes(List<SecondData> measurements,
        int wavelengthBoxSize) {

    // calculate boxes
    int waveLengthWindow = measurements.size() / 2 - 0;
    int boxes = (int) Math.ceil((double) waveLengthWindow / (double) wavelengthBoxSize);

    double[] largestBoxedResponses = new double[boxes];

    // prepare data for FFT
    double[] data = new double[measurements.size()];

    int total = 0;
    for (SecondData measurement : measurements) {
        data[total++] = measurement.getPower();
    }/*  www  .j av a  2  s .  c o  m*/

    // perform FFT
    DoubleFFT_1D fft = new DoubleFFT_1D(measurements.size());
    fft.realForward(data);

    // perform spectral analysis
    double[] spectrum = new double[measurements.size() / 2];
    for (int i = 0; i < measurements.size() / 2; i++) {
        spectrum[i] = Math.sqrt(Math.pow(data[2 * i], 2) + Math.pow(data[2 * i + 1], 2));
    }

    // loop through frequencies and select the largest ones
    double frequencyPiece = (double) 0.5 / (spectrum.length - 1);
    for (int i = 1; i < spectrum.length; i++) {
        // greatest frequency in each box goes into list
        double frequency = (double) i * frequencyPiece;
        double wavelength = (double) 1.0 / frequency;

        double amplitude = spectrum[i];

        if (wavelength < 600 && amplitude / frequency > 500 * measurements.size()) {
            //System.out.println(wavelength + ": " + amplitude / frequency);
            // only select the wavelengths with high enough power for our choosing

            if (wavelength < (measurements.size() / 2)) {
                int wavelengthBox = (int) (wavelength / wavelengthBoxSize);
                largestBoxedResponses[wavelengthBox] = Math.max(amplitude / frequency,
                        largestBoxedResponses[wavelengthBox]);
            }
        }
    }

    return largestBoxedResponses;
}

From source file:embedding.ExampleJava2D2PDF.java

/**
 * Creates a PDF file. The contents are painted using a Graphics2D implementation that
 * generates an PDF file./*from   w w  w . j  a  va2s  . co m*/
 * @param outputFile the target file
 * @throws IOException In case of an I/O error
 * @throws ConfigurationException if an error occurs configuring the PDF output
 */
public void generatePDF(File outputFile) throws IOException, ConfigurationException {
    OutputStream out = new java.io.FileOutputStream(outputFile);
    out = new java.io.BufferedOutputStream(out);
    try {

        //Instantiate the PDFDocumentGraphics2D instance
        PDFDocumentGraphics2D g2d = new PDFDocumentGraphics2D(false);
        g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());

        //Configure the G2D with the necessary fonts
        configure(g2d, createAutoFontsConfiguration());

        //Set up the document size
        Dimension pageSize = new Dimension((int) Math.ceil(UnitConv.mm2pt(210)),
                (int) Math.ceil(UnitConv.mm2pt(297))); //page size A4 (in pt)
        g2d.setupDocument(out, pageSize.width, pageSize.height);
        g2d.translate(144, 72); //Establish some page borders

        //A few rectangles rotated and with different color
        Graphics2D copy = (Graphics2D) g2d.create();
        int c = 12;
        for (int i = 0; i < c; i++) {
            float f = ((i + 1) / (float) c);
            Color col = new Color(0.0f, 1 - f, 0.0f);
            copy.setColor(col);
            copy.fillRect(70, 90, 50, 50);
            copy.rotate(-2 * Math.PI / c, 70, 90);
        }
        copy.dispose();

        //Some text
        g2d.rotate(-0.25);
        g2d.setColor(Color.RED);
        g2d.setFont(new Font("sans-serif", Font.PLAIN, 36));
        g2d.drawString("Hello world!", 140, 140);
        g2d.setColor(Color.RED.darker());
        g2d.setFont(new Font("serif", Font.PLAIN, 36));
        g2d.drawString("Hello world!", 140, 180);

        pageSize = new Dimension(pageSize.height, pageSize.width);
        g2d.nextPage(pageSize.width, pageSize.height);

        //Demonstrate painting rich text
        String someHTML = "<html><body style=\"font-family:Verdana\">" + "<p>Welcome to <b>page 2!</b></p>"
                + "<h2>PDFDocumentGraphics2D Demonstration</h2>"
                + "<p>We can <i>easily</i> paint some HTML here!</p>" + "<p style=\"color:green;\">"
                + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin accumsan"
                + " condimentum ullamcorper. Sed varius quam id arcu fermentum luctus. Praesent"
                + " nisi ligula, cursus sed vestibulum vel, sodales sed lectus.</p>" + "</body></html>";
        JEditorPane htmlComp = new JEditorPane();
        htmlComp.setContentType("text/html");
        htmlComp.read(new StringReader(someHTML), null);
        htmlComp.setSize(new Dimension(pageSize.width - 72, pageSize.height - 72));
        //htmlComp.setBackground(Color.ORANGE);
        htmlComp.validate();
        htmlComp.printAll(g2d);

        //Cleanup
        g2d.finish();
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:edu.umd.cfar.lamp.viper.geometry.BoundingBox.java

/**
 * Creates a bounding box in double coordinates. Just casts the parameters
 * to ints, for now./* www  .ja  v  a2 s.co m*/
 * 
 * @param leftEdge
 *            the left edge
 * @param bottomEdge
 *            the bottom edge (top in screen coordinates)
 * @param width
 *            the width of the box
 * @param height
 *            the height of the box
 */
public BoundingBox(double leftEdge, double bottomEdge, double width, double height) {
    rect = new Rectangle((int) leftEdge, (int) bottomEdge, (int) Math.ceil(width), (int) Math.ceil(height));
}

From source file:no.met.jtimeseries.marinogram.MarinogramPressurePlot.java

private XYPlot createPlot(TimeZone timezone, boolean plotPressure) {
    ChartPlotter plotter = null;/*  w  ww.java  2  s .  c  om*/
    if (plotPressure) {
        plotter = new ChartPlotter();
        // default setting
        plotter.setHeight(this.getHeight());
        plotter.setWidth(this.getWidth());
        plotter.setPlotDefaultProperties("", "");
        NumberPhenomenon pressure = getLocationForecastDataModel()
                .getPhenomenen(PhenomenonName.Pressure.toString(), NumberPhenomenon.class);
        List<Date> shortTermTime = pressure.getTime();
        Color pressureColor = new Color(11, 164, 42);

        PlotStyle.Builder pressureStyleBuilder = new PlotStyle.Builder(
                messages.getString("parameter.pressure") + " (hPa)");
        PlotStyle plotStyle = pressureStyleBuilder.spline(SplineStyle.HYBRID).ticks(4).difference(50.0d)
                .seriesColor(pressureColor).labelColor(pressureColor).build();
        plotter.addLineChart(TimeBase.SECOND, pressure, plotStyle);
        //plotter.formalizeRangeAxisWithMargins(plotter.getRangeAxisIndex() - 1, 950, 1050);

        double tick = (pressure.getMaxValue() - pressure.getMinValue()) / 2;
        tick = Math.ceil(tick / 10) * 10;
        double lowBound = Math.floor(pressure.getMinValue() / (tick)) * (tick);
        lowBound = lowBound - tick / 2;
        double upperBound = lowBound + tick * 4;

        //replicate the range axis 
        NumberAxis referenceAxis = (NumberAxis) plotter.getPlot().getRangeAxis();
        referenceAxis.setTickUnit(new NumberTickUnit(tick));
        referenceAxis.setLowerBound(lowBound);
        referenceAxis.setUpperBound(upperBound);
        NumberAxis numberAxis = new NumberAxis();
        numberAxis.setLabelPaint(pressureColor);
        numberAxis.setTickLabelPaint(referenceAxis.getTickLabelPaint());
        //numberAxis.setLowerMargin(ChartPlotter.LOWER_PLOT_MARGIN);
        numberAxis.setRange(referenceAxis.getLowerBound(), referenceAxis.getUpperBound());
        numberAxis.setTickUnit(referenceAxis.getTickUnit());
        //numberAxis.setRangeWithMargins(950, 1050);
        plotter.getPlot().setRangeAxis(1, numberAxis);

        //first set domain date format and then add hour based domain grid lines
        //TODO: wrap this inside the addHourBasedDomainGridLines for simplicity
        Date minDate = shortTermTime.get(0);
        Date maxDate = shortTermTime.get(shortTermTime.size() >= 48 ? 48 : shortTermTime.size() - 1);
        plotter.setDomainRange(minDate, maxDate);
        plotter.setDomainDateFormat(timezone, "HH");
        plotter.getPlot().setOutlineVisible(true);
        //set domain range after (must) plot all the data
        plotter.addHourBasedDomainGridLines();
        //invisible domain axis
        plotter.getPlot().getDomainAxis().setTickLabelsVisible(false);
        // add markers
        plotter.addDomainMarkers(shortTermTime, timezone, locale);

    }

    return plotter.getPlot();

}

From source file:bftsmart.tom.ServiceProxy.java

/**
 * Constructor//from w ww . jav a  2  s  .co m
 *
 * @param processId Process id for this client (should be different from replicas)
 * @param configHome Configuration directory for BFT-SMART
 * @param replyComparator used for comparing replies from different servers
 *                        to extract one returned by f+1
 * @param replyExtractor used for extracting the response from the matching
 *                       quorum of replies
 */
public ServiceProxy(int processId, String configHome, Comparator<byte[]> replyComparator,
        Extractor replyExtractor) {
    if (configHome == null) {
        init(processId);
    } else {
        init(processId, configHome);
    }
    if (getViewManager().getStaticConf().isBFT()) {
        replyQuorum = (int) Math
                .ceil((getViewManager().getCurrentViewN() + getViewManager().getCurrentViewF()) / 2) + 1;
    } else {
        replyQuorum = (int) Math.ceil((getViewManager().getCurrentViewN()) / 2) + 1;
    }

    replies = new TOMMessage[getViewManager().getCurrentViewN()];

    comparator = (replyComparator != null) ? replyComparator : new Comparator<byte[]>() {
        @Override
        public int compare(byte[] o1, byte[] o2) {
            return Arrays.equals(o1, o2) ? 0 : -1;
        }
    };

    extractor = (replyExtractor != null) ? replyExtractor : new Extractor() {

        @Override
        public TOMMessage extractResponse(TOMMessage[] replies, int sameContent, int lastReceived) {
            return replies[lastReceived];
        }
    };
    replyListener = null;
}

From source file:com.forsrc.utils.MyRsa2Utils.java

/**
 * Encrypt string.//from ww  w .  ja  va  2  s.co  m
 *
 * @param publicKey the public key
 * @param plaintext the plaintext
 * @return the string
 * @throws RsaException the rsa exception
 */
public static String encrypt(PublicKey publicKey, String plaintext) throws RsaException {
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance(RsaKey.ALGORITHM, new org.bouncycastle.jce.provider.BouncyCastleProvider());
    } catch (NoSuchAlgorithmException e) {
        throw new RsaException(e);
    } catch (NoSuchPaddingException e) {
        throw new RsaException(e);
    }
    try {
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    } catch (InvalidKeyException e) {
        throw new RsaException(e);
    }
    byte[] data = plaintext.getBytes();
    int blockSize = cipher.getBlockSize();
    blockSize = blockSize == 0 ? 117 : blockSize;
    int outputSize = cipher.getOutputSize(data.length);
    int count = (int) Math.ceil(data.length / blockSize) + 1;

    byte[] output = new byte[outputSize * count];
    try {

        int i = 0;
        int start = 0;
        int outputStart = 0;
        do {
            start = i * blockSize;
            outputStart = i * outputSize;
            if (data.length - start >= blockSize) {
                cipher.doFinal(data, start, blockSize, output, outputStart);
            } else {
                cipher.doFinal(data, start, data.length - start, output, outputStart);
            }
            i++;
        } while (data.length - start - blockSize >= 0);

    } catch (IllegalBlockSizeException e) {
        throw new RsaException(e);
    } catch (BadPaddingException e) {
        throw new RsaException(e);
    } catch (ShortBufferException e) {
        throw new RsaException(e);
    }
    return new String(new Base64().encode(output));
}

From source file:Main.java

/**
 * Goal is to return a reasonable string representation
 * of x, using at most width spaces.  (If the parameter width is
 * unreasonably big or small, its value is adjusted to
 * lie in the range 6 to 25.)/*from ww  w  .  j  a  v a 2s .  c  om*/
 *
 * @param x value to create string representation of.
 * @param width maximum number of spaces used in string representation, if possible.
 * @return a string representation for x.  If x is Double.NaN, "undefined" is returned.
 *         If x is infinite, "INF" or "-INF" is returned.
 */
public static String realToString(double x, int width) {
    width = Math.min(25, Math.max(6, width));
    if (Double.isNaN(x))
        return "undefined";
    if (Double.isInfinite(x))
        if (x < 0)
            return "-INF";
        else
            return "INF";
    String s = String.valueOf(x);
    if (Math.rint(x) == x && Math.abs(x) < 5e15 && s.length() <= (width + 2))
        return String.valueOf((long) x); // return string without trailing ".0"
    if (s.length() <= width)
        return s;
    boolean neg = false;
    if (x < 0) {
        neg = true;
        x = -x;
        width--;
        s = String.valueOf(x);
    }
    long maxForNonExp = 5 * (long) Math.pow(10, width - 2);
    if (x >= 0.0005 && x <= maxForNonExp && (s.indexOf('E') == -1 && s.indexOf('e') == -1)) {
        s = round(s, width);
        s = trimZeros(s);
    } else if (x > 1) { // construct exponential form with positive exponent
        long power = (long) Math.floor(Math.log(x) / Math.log(10));
        String exp = "E" + power;
        int numlength = width - exp.length();
        x = x / Math.pow(10, power);
        s = String.valueOf(x);
        s = round(s, numlength);
        s = trimZeros(s);
        s += exp;
    } else { // constuct exponential form with negative argument
        long power = (long) Math.ceil(-Math.log(x) / Math.log(10));
        String exp = "E-" + power;
        int numlength = width - exp.length();
        x = x * Math.pow(10, power);
        s = String.valueOf(x);
        s = round(s, numlength);
        s = trimZeros(s);
        s += exp;
    }
    if (neg)
        return "-" + s;
    else
        return s;
}

From source file:com.smithsmodding.armory.api.crafting.blacksmiths.recipe.VanillaAnvilRecipe.java

@Override
public void onRecipeUsed(TileEntityBlackSmithsAnvil pEntity) {
    boolean tCreativePlayerConnected = false;

    for (UUID playerId : iEntity.getWatchingPlayers()) {
        if (PlayerManager.getInstance().getServerSidedJoinedMap().get(playerId).capabilities.isCreativeMode)
            tCreativePlayerConnected = true;
    }/*w  ww .  jav a2  s  .  co  m*/

    if (!tCreativePlayerConnected) {
        float tExperience = XPUtil.getExperienceForLevel(iMaximumCost);
        int tXPPerPlayer = (int) Math.ceil(tExperience / (float) pEntity.getConnectedPlayerCount());

        for (UUID playerId : pEntity.getWatchingPlayers()) {
            XPUtil.addPlayerXP(PlayerManager.getInstance().getServerSidedJoinedMap().get(playerId),
                    -tXPPerPlayer);
        }
    }
}

From source file:com.aptech.action.ProductAction.java

@SkipValidation
public String index() throws Exception {
    try {//ww  w  . ja v a 2s. com
        Integer page;
        Double totalNumberOfRecords = 0.0;
        Double numberOfRecordsPerPage = 4.0;
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
                .get(ServletActionContext.HTTP_REQUEST);
        if (request.getParameter("page") != null) {
            page = Integer.parseInt(request.getParameter("page"));
        } else {
            page = 1;
        }
        totalNumberOfRecords = dao.count().doubleValue();
        Double startIndex = (page * numberOfRecordsPerPage) - numberOfRecordsPerPage;
        Double temp = Math.ceil(totalNumberOfRecords / numberOfRecordsPerPage);
        maxPage = temp.intValue();
        if (totalNumberOfRecords % 2 != 0) {
            maxPage += 1;
        }
        listProduct = dao.paging(startIndex.intValue(), numberOfRecordsPerPage.intValue());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return SUCCESS;
}

From source file:jurls.core.utils.MatrixImage.java

public void draw(ParameterizedFunction f) {
    int numParam = f.numberOfParameters();
    int cw = (int) Math.ceil(Math.sqrt(numParam));
    int ch = numParam / cw;
    draw((x, y) -> {//from  w  ww  .j av a2 s  .c  o m
        int i = y * ch + x;
        if (i < numParam) {
            return f.getParameter(i);
        }
        return 0;
    }, cw, ch, -1.0, 1.0);

}