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:gdsc.smlm.ij.plugins.LoadLocalisations.java

private boolean getZDepth(List<LocalisationModel> localisations) {
    double min = localisations.get(0).getZ();
    double max = min;
    for (LocalisationModel l : localisations) {
        if (min > l.getZ())
            min = l.getZ();//from w  w  w  .ja  v a 2s.  c om
        if (max < l.getZ())
            max = l.getZ();
    }

    maxz = FastMath.min(maxz, max);
    minz = FastMath.max(minz, min);

    String msg = String.format("%d localisations with %.2f <= z <= %.2f", localisations.size(), min, max);

    min = Math.floor(min);
    max = Math.ceil(max);

    GenericDialog gd = new GenericDialog(TITLE);
    gd.addMessage(msg);
    gd.addCheckbox("Limit Z-depth", limitZ);
    gd.addSlider("minZ", min, max, minz);
    gd.addSlider("maxZ", min, max, maxz);
    gd.showDialog();
    if (gd.wasCanceled() || gd.invalidNumber()) {
        return false;
    }
    limitZ = gd.getNextBoolean();
    minz = gd.getNextNumber();
    maxz = gd.getNextNumber();
    return true;
}

From source file:com.github.rinde.rinsim.scenario.generator.PoissonIntensityTest.java

/**
 * Tests whether the Poisson process (crudely) approximates the intensity
 * function when a large number of runs is done.
 *//*from  ww w .  ja  v a  2 s .  co  m*/
@Test
public void intensityApproximationPoissonProcessTest() {
    final RandomGenerator rng = new MersenneTwister(123);

    final TimeSeriesGenerator pp = TimeSeries.nonHomogenousPoisson(100d, intensityFunction);

    final Multiset<Double> ms = TreeMultiset.create();
    final int repetitions = 10000;
    for (int i = 0; i < repetitions; i++) {
        final List<Double> times = pp.generate(rng.nextLong());
        for (final Double d : times) {
            ms.add(new Double(Math.ceil(d)));
        }
    }
    for (final Multiset.Entry<Double> entry : ms.entrySet()) {
        final double exp = IntensityFunctions.areaByIntegration(intensityFunction, entry.getElement() - 1d,
                entry.getElement());

        final double observation = entry.getCount() / (double) repetitions;
        assertEquals(exp, observation, 0.05);
    }
}

From source file:etymology.util.EtyMath.java

public static double avgLnGamma(double value) {
    int floor = (int) Math.floor(value);
    double diff = Math.abs(value - floor);
    if (diff <= 0.01) {
        return lnFactorial(floor - 1);
    }//from  w ww .ja va 2 s. c o m

    int ceil = (int) Math.ceil(value);
    diff = Math.abs(ceil - value);
    if (diff <= 0.01) {
        return lnFactorial(ceil - 1);
    }

    double logFactCeil = lnFactorial(ceil);
    double logFactFloor = lnFactorial(floor);
    double overFloor = value - floor;
    return (overFloor * logFactFloor) + (1 - overFloor) * logFactCeil;
}

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

/**
 * Generates a bulk assignment plan to be used on cluster startup using a
 * simple round-robin assignment./*from  w w w  .jav a  2  s .c  o m*/
 * <p>
 * Takes a list of all the entityGroups and all the servers in the cluster and
 * returns a map of each server to the entityGroups that it should be assigned.
 * <p>
 * Currently implemented as a round-robin assignment. Same invariant as load
 * balancing, all servers holding floor(avg) or ceiling(avg).
 * 
 * TODO: Use block locations from HDFS to place entityGroups with their blocks
 * 
 * @param entityGroups all entityGroups
 * @param servers all servers
 * @return map of server to the entityGroups it should take, or null if no
 *         assignment is possible (ie. no entityGroups or no servers)
 */
public Map<ServerName, List<EntityGroupInfo>> roundRobinAssignment(List<EntityGroupInfo> entityGroups,
        List<ServerName> servers) {
    if (entityGroups.isEmpty() || servers.isEmpty()) {
        return null;
    }
    Map<ServerName, List<EntityGroupInfo>> assignments = new TreeMap<ServerName, List<EntityGroupInfo>>();
    int numEntityGroups = entityGroups.size();
    int numServers = servers.size();
    int max = (int) Math.ceil((float) numEntityGroups / numServers);
    int serverIdx = 0;
    if (numServers > 1) {
        serverIdx = RANDOM.nextInt(numServers);
    }
    int entityGroupIdx = 0;
    for (int j = 0; j < numServers; j++) {
        ServerName server = servers.get((j + serverIdx) % numServers);
        List<EntityGroupInfo> serverEntityGroups = new ArrayList<EntityGroupInfo>(max);
        for (int i = entityGroupIdx; i < numEntityGroups; i += numServers) {
            serverEntityGroups.add(entityGroups.get(i % numEntityGroups));
        }
        assignments.put(server, serverEntityGroups);
        entityGroupIdx++;
    }
    return assignments;
}

From source file:com.daphne.es.personal.calendar.web.controller.CalendarController.java

@RequestMapping(value = "/new", method = RequestMethod.GET)
public String showNewForm(
        @RequestParam(value = "start", required = false) @DateTimeFormat(pattern = dataFormat) Date start,
        @RequestParam(value = "end", required = false) @DateTimeFormat(pattern = dataFormat) Date end,
        Model model) {/*from  w ww  .ja  v a 2 s. c  o m*/

    setColorList(model);

    Calendar calendar = new Calendar();
    calendar.setLength(1);
    if (start != null) {
        calendar.setStartDate(start);
        calendar.setLength((int) Math.ceil(1.0 * (end.getTime() - start.getTime()) / oneDayMillis));
        if (DateUtils.isSameDay(start, end)) {
            calendar.setLength(1);
        }
        if (!"00:00:00".equals(DateFormatUtils.format(start, "HH:mm:ss"))) {
            calendar.setStartTime(start);
        }
        if (!"00:00:00".equals(DateFormatUtils.format(end, "HH:mm:ss"))) {
            calendar.setEndTime(end);
        }

    }
    model.addAttribute("model", calendar);
    return viewName("newForm");
}

From source file:CheckFonts.java

/**
 * ?  ??  dialog base unit'.//from www  .ja v  a2 s.  c  om
 * 
 * ? :   - ?  ????  ,   - ??  ????
 *  .
 */
protected static Dimension getDimension(ResourceDialog dialog, String text) throws Exception {
    int fontPixelsSize = (int) Math.round(dialog.pointsize * 96.0 / 72);

    Font f = getDialogFont(dialog).deriveFont(dialog.italic != 0 ? Font.ITALIC : 0, fontPixelsSize);

    // BufferedImage img = new BufferedImage(1024, 512, BufferedImage.TYPE_INT_RGB);
    // Graphics gr = img.getGraphics();
    // FontMetrics fm = gr.getFontMetrics(f);
    // r = fm.stringWidth(text);

    FontRenderContext frc = new FontRenderContext(null, false, false);
    Rectangle2D strDialogUnits = f.getStringBounds("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", frc);
    // ? ???   - http://support.microsoft.com/kb/125681
    double fullWidth = strDialogUnits.getWidth();
    double fullHeight = strDialogUnits.getHeight();
    long avgWidth = Math.round(Math.ceil(fullWidth) / 26 + 1) / 2;
    long avgHeight = Math.round(Math.ceil(fullHeight));
    double dbuX = avgWidth / 4.0;
    double dbuY = avgHeight / 8.0;

    Rectangle2D strRect = f.getStringBounds(text.replace("&", ""), frc);
    int w = (int) Math.ceil(strRect.getWidth() / dbuX);

    int h = (int) Math.ceil(strRect.getHeight() / dbuY);

    return new Dimension(w, h);
}

From source file:es.ucm.fdi.dalgs.academicTerm.repository.AcademicTermRepository.java

public Integer numberOfPages(Boolean showAll) {

    Query query = null;/*  w w  w . ja  v  a2s  .c o m*/
    if (showAll)
        query = em.createNativeQuery("select count(*) from academicterm");
    else
        query = em.createNativeQuery("select count(*) from academicterm where isDeleted='false'");

    logger.info(query.getSingleResult().toString());
    double dou = Double.parseDouble(query.getSingleResult().toString()) / ((double) noOfRecords);
    return (int) Math.ceil(dou);

}

From source file:com.opengamma.analytics.financial.model.option.pricing.fourier.FFTModelGreeks.java

/**
 * /*www .j  av  a2s  . c o m*/
  * @param forward The forward value of the underlying
  * @param discountFactor 
  * @param t Time to expiry
  * @param isCall true for call 
  * @param ce The Characteristic Exponent (log of characteristic function) of the returns of the underlying
  * @param lowestStrike The lowest strike to return (the actual value will depend on the set up, but is guaranteed to be less than this) 
  * @param highestStrike The highest strike to return (the actual value will depend on the set up, but is guaranteed to be greater than this) 
  * @param minStrikesDisplayed minimum number of strikes returned (actual number depends on set up) 
  * @param limitSigma An estimate of the implied vol used to calculate limits in the numerical routines 
  * @param alpha Regularization factor. Values of 0 or -1 are not allowed. -0.5 is recommended  
  * @param tol Tolerance - smaller values give higher accuracy 
 * @return an array of arrays where is first array is the strikes, the second the prices, the first the derivatives of price wrt the first parameter etc 
 */
//TODO this is cut and paste from FFTPricer - the calculation of the sample size and spacing should be extracted 
public double[][] getGreeks(final double forward, final double discountFactor, final double t,
        final boolean isCall, final MartingaleCharacteristicExponent ce, final double lowestStrike,
        final double highestStrike, final int minStrikesDisplayed, final double limitSigma, final double alpha,
        final double tol) {

    Validate.notNull(ce, "characteristic exponent");
    Validate.isTrue(tol > 0.0, "need tol > 0");
    Validate.isTrue(alpha != 0.0 && alpha != -1.0, "alpha cannot be -1 or 0");

    Validate.isTrue(lowestStrike <= forward, "need lowestStrike <= forward");
    Validate.isTrue(highestStrike >= forward, "need highestStrike >= forward");
    Validate.isTrue(limitSigma > 0.0, "need limitSigma > 0");

    double kMax;
    final double limitSigmaRootT = limitSigma * Math.sqrt(t);
    final double atm = NORMAL.getCDF(limitSigmaRootT / 2.0);

    if (alpha > 0) {
        kMax = -Math.log((2 * atm - 1) * tol) / alpha;
    } else if (alpha < -1.0) {
        kMax = Math.log((2 * atm - 1) * tol) / (1 + alpha);
    } else {
        kMax = -Math.log(2 * (1 - atm) * tol) * Math.max(-1.0 / alpha, 1 / (1 + alpha));
    }

    final EuropeanCallFourierTransform psi = new EuropeanCallFourierTransform(ce);
    final Function1D<ComplexNumber, ComplexNumber> psiFunction = psi.getFunction(t);
    final double xMax = LIMIT_CALCULATOR.solve(psiFunction, alpha, tol);

    double deltaK;
    if (highestStrike == lowestStrike) {
        deltaK = Math.PI / xMax;
    } else {
        deltaK = Math.min(Math.log(highestStrike / lowestStrike) / (minStrikesDisplayed - 1), Math.PI / xMax);
    }

    final double log2 = Math.log(2);
    final int twoPow = (int) Math.ceil(Math.log(kMax / deltaK) / log2);

    final int n = (int) Math.pow(2, twoPow);
    final double delta = 2 * Math.PI / n / deltaK;
    final int m = (int) (xMax * deltaK * n / 2 / Math.PI);

    final int nLowStrikes = (int) Math.ceil(Math.log(forward / lowestStrike) / deltaK);
    final int nHighStrikes = (int) Math.ceil(Math.log(highestStrike / forward) / deltaK);

    return getGreeks(forward, discountFactor, t, isCall, ce, nLowStrikes, nHighStrikes, alpha, delta, n, m);
}

From source file:edu.umn.cs.spatialHadoop.indexing.GridPartitioner.java

@Override
public void readFields(DataInput in) throws IOException {
    this.x = in.readDouble();
    this.y = in.readDouble();
    this.tileWidth = in.readDouble();
    this.tileHeight = in.readDouble();
    this.numTiles = in.readInt();
    this.numColumns = (int) Math.round(Math.sqrt(numTiles));
    this.numRows = (int) Math.ceil(numTiles / numColumns);
}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}/*from   w w  w.  jav a  2  s . c om*/
 */
@Override
public final byte[] mac(byte[] dataToMac, byte[] key) throws McbpCryptoException {
    // First create an array of MAC BLOCK Size all set to 0x00
    int macSize = (int) Math.ceil(((double) dataToMac.length + 1) / 8) * 8;
    byte[] mac = new byte[macSize];
    System.arraycopy(dataToMac, 0, mac, 0, dataToMac.length);

    // Add the padding at the relevant location. The padding is defined 0x80, 0x00 ... 0x00
    mac[dataToMac.length] = (byte) 0x80;

    final byte[] keyL = Arrays.copyOfRange(key, 0, key.length / 2);
    final byte[] keyR = Arrays.copyOfRange(key, key.length / 2, key.length);

    // ----- Perform DES3 Encryption to Calculate MAC ---------
    byte[] desResult = new byte[8];
    // The the 8 most right bytes of the first desCbc encryption
    System.arraycopy(desCbc(mac, keyL, Mode.ENCRYPT), macSize - 8, desResult, 0, 8);
    byte[] bMac = des(desResult, keyR, Mode.DECRYPT);
    byte[] result = des(bMac, keyL, Mode.ENCRYPT);

    // Clear temporary data structures
    Utils.clearByteArray(bMac);
    Utils.clearByteArray(mac);
    Utils.clearByteArray(keyL);
    Utils.clearByteArray(keyR);
    Utils.clearByteArray(desResult);

    return result;
}