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:edu.umn.cs.spatialHadoop.nasa.SpatioAggregateQueries.java

/**
 * Performs a spatio-temporal aggregate query on an indexed directory
 * @param inFile/*w  w  w  .ja  v  a 2  s  . com*/
 * @param params
 * @throws ParseException 
 * @throws IOException 
 * @throws InterruptedException 
 */
public static AggregateQuadTree.Node aggregateQuery(Path inFile, OperationsParams params)
        throws ParseException, IOException, InterruptedException {
    // 1- Find matching temporal partitions
    final FileSystem fs = inFile.getFileSystem(params);
    Vector<Path> matchingPartitions = selectTemporalPartitions(inFile, params);

    // 2- Find all matching files (AggregateQuadTrees) in matching partitions
    final Rectangle spatialRange = params.getShape("rect", new Rectangle()).getMBR();
    // Convert spatialRange from lat/lng space to Sinusoidal space
    double cosPhiRad = Math.cos(spatialRange.y1 * Math.PI / 180);
    double southWest = spatialRange.x1 * cosPhiRad;
    double southEast = spatialRange.x2 * cosPhiRad;
    cosPhiRad = Math.cos(spatialRange.y2 * Math.PI / 180);
    double northWest = spatialRange.x1 * cosPhiRad;
    double northEast = spatialRange.x2 * cosPhiRad;
    spatialRange.x1 = Math.min(northWest, southWest);
    spatialRange.x2 = Math.max(northEast, southEast);
    // Convert to the h v space used by MODIS
    spatialRange.x1 = (spatialRange.x1 + 180.0) / 10.0;
    spatialRange.x2 = (spatialRange.x2 + 180.0) / 10.0;
    spatialRange.y2 = (90.0 - spatialRange.y2) / 10.0;
    spatialRange.y1 = (90.0 - spatialRange.y1) / 10.0;
    // Vertically flip because the Sinusoidal space increases to the south
    double tmp = spatialRange.y2;
    spatialRange.y2 = spatialRange.y1;
    spatialRange.y1 = tmp;
    // Find the range of cells in MODIS Sinusoidal grid overlapping the range
    final int h1 = (int) Math.floor(spatialRange.x1);
    final int h2 = (int) Math.ceil(spatialRange.x2);
    final int v1 = (int) Math.floor(spatialRange.y1);
    final int v2 = (int) Math.ceil(spatialRange.y2);
    PathFilter rangeFilter = new PathFilter() {
        @Override
        public boolean accept(Path p) {
            Matcher matcher = MODISTileID.matcher(p.getName());
            if (!matcher.matches())
                return false;
            int h = Integer.parseInt(matcher.group(1));
            int v = Integer.parseInt(matcher.group(2));
            return h >= h1 && h < h2 && v >= v1 && v < v2;
        }
    };

    final Vector<Path> allMatchingFiles = new Vector<Path>();

    for (Path matchingPartition : matchingPartitions) {
        // Select all matching files
        FileStatus[] matchingFiles = fs.listStatus(matchingPartition, rangeFilter);
        for (FileStatus matchingFile : matchingFiles) {
            allMatchingFiles.add(matchingFile.getPath());
        }
    }

    //noinspection SizeReplaceableByIsEmpty
    if (allMatchingFiles.isEmpty())
        return null;

    final int resolution = AggregateQuadTree.getResolution(fs, allMatchingFiles.get(0));

    // 3- Query all matching files in parallel
    List<Node> threadsResults = Parallel.forEach(allMatchingFiles.size(),
            new RunnableRange<AggregateQuadTree.Node>() {
                @Override
                public Node run(int i1, int i2) {
                    Node threadResult = new AggregateQuadTree.Node();
                    for (int i_file = i1; i_file < i2; i_file++) {
                        Path matchingFile = allMatchingFiles.get(i_file);
                        try {
                            Matcher matcher = MODISTileID.matcher(matchingFile.getName());
                            matcher.matches(); // It has to match
                            int h = Integer.parseInt(matcher.group(1));
                            int v = Integer.parseInt(matcher.group(2));
                            // Clip the query region and normalize in this tile
                            Rectangle translated = spatialRange.translate(-h, -v);
                            int x1 = (int) (Math.max(translated.x1, 0) * resolution);
                            int y1 = (int) (Math.max(translated.y1, 0) * resolution);
                            int x2 = (int) (Math.min(translated.x2, 1.0) * resolution);
                            int y2 = (int) (Math.min(translated.y2, 1.0) * resolution);
                            AggregateQuadTree.Node fileResult = AggregateQuadTree.aggregateQuery(fs,
                                    matchingFile, new java.awt.Rectangle(x1, y1, (x2 - x1), (y2 - y1)));
                            threadResult.accumulate(fileResult);
                        } catch (Exception e) {
                            throw new RuntimeException("Error reading file " + matchingFile, e);
                        }
                    }
                    return threadResult;
                }
            });
    AggregateQuadTree.Node finalResult = new AggregateQuadTree.Node();
    for (Node threadResult : threadsResults) {
        finalResult.accumulate(threadResult);
    }
    numOfTreesTouchesInLastRequest = allMatchingFiles.size();
    return finalResult;
}

From source file:com.jennifer.ui.chart.brush.EqualizerBrush.java

@Override
public Object draw() {
    for (int i = 0; i < count; i++) {
        double startX = x.get(i) - half_width;

        for (int j = 0, jLen = target.length(); j < jLen; j++) {
            Transform barGroup = root.group();

            double startY = y.get(chart.dataDouble(i, target.getString(j)));
            double padding = 1.5;
            double eY = zeroY;
            int eIndex = 0;

            JSONObject o = new JSONObject().put("x", startX).put("width", barWidth).put("fill",
                    color((int) Math.floor(eIndex / gap)));

            if (startY <= zeroY) {
                while (eY > startY) {
                    double unitHeight = (eY - unit < startY) ? Math.abs(eY - startY) : unit;

                    o.put("y", eY - unitHeight).put("height", unitHeight);

                    eY -= unitHeight + padding;
                    eIndex++;// w  ww.ja  v a2s  . c o m
                }
            } else {
                while (eY < startY) {
                    double unitHeight = (eY + unit > startY) ? Math.abs(eY - startY) : unit;

                    o.put("y", eY).put("height", unitHeight);

                    eY += unitHeight + padding;
                    eIndex++;

                }
            }

            barGroup.rect(o);

            startX += barWidth + innerPadding;
        }
    }

    return new JSONObject().put("root", root);
}

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

@Override
public CA generateCA(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 www  .j  a v a 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("First phase over.");
    System.out.println("Partial array size: " + n);
    System.out.println(new Date());
    System.out.println("Number of uncovered orbits: " + uncovOrbNum);

    ListCAExt remCA = new ListCAExt(t, k, v);
    this.secondStage(remCA);
    ListCA ca = new ListCAExt(t, k, v);
    ca.join(partialCa);
    ca.join(remCA);

    ((ListCAExt) ca).copyInfo(remCA);

    System.out.println("Number of rows added in second phase: " + remCA.getNumRows());

    Group g = partialCa.getGroup();
    ListCA fullCA = g.develop(ca);

    System.out.println(new Date());

    /*ArrayCA testCA = new ArrayCA(fullCA);
    ColGroup cols = new ColGroup(new int[0]);
    System.out.println("\nThis " + (testCA.isCompleteCA(cols) ? "is a CA" 
    : "is not a CA\n"));*/

    return fullCA;
}

From source file:net.sf.keystore_explorer.utilities.io.HexUtil.java

private static String getHexClearLineDump(byte[] bytes, int len) {
    StringBuffer sbHex = new StringBuffer();
    StringBuffer sbClr = new StringBuffer();

    for (int cnt = 0; cnt < len; cnt++) {
        // Convert byte to int
        byte b = bytes[cnt];
        int i = b & 0xFF;

        // First part of byte will be one hex char
        int i1 = (int) Math.floor(i / 16);

        // Second part of byte will be one hex char
        int i2 = i % 16;

        // Get hex characters
        sbHex.append(Character.toUpperCase(Character.forDigit(i1, 16)));
        sbHex.append(Character.toUpperCase(Character.forDigit(i2, 16)));

        if ((cnt + 1) < len) {
            // Divider between hex characters
            sbHex.append(' ');
        }// w w  w .ja v  a 2  s  .  c  o  m

        // Get clear character

        // Character to display if character not defined in Unicode or is a
        // control charcter
        char c = '.';

        // Not a control character and defined in Unicode
        if ((!Character.isISOControl((char) i)) && (Character.isDefined((char) i))) {
            Character clr = new Character((char) i);
            c = clr.charValue();
        }

        sbClr.append(c);
    }

    /*
     * Put both dumps together in one string (hex, clear) with appropriate
     * padding between them (pad to array length)
     */
    StringBuffer strBuff = new StringBuffer();

    strBuff.append(sbHex.toString());

    int i = bytes.length - len;
    for (int cnt = 0; cnt < i; cnt++) {
        strBuff.append("   "); // Each missing byte takes up three spaces
    }

    strBuff.append("   "); // The gap between hex and clear output is three
    // spaces
    strBuff.append(sbClr.toString());

    return strBuff.toString();
}

From source file:com.amazon.feeds.formats.SampleFormatB.java

/**
 * Populate sample feed with dummy items.
 *
 * @param size The size of the feed.//from w  w w. jav a 2  s. com
 */
@Override
public void populate(int size) {

    for (int i = 0; i < size; i++) {
        currentItemID++;
        Asset asset = new Asset();
        assets.add(asset);
    }

    // add category with maximum items
    Container categoryMaxItems = new Container(size);
    containers.add(categoryMaxItems);
    currentContainerID++;
    // add category with a single item
    Container categorySingleItem = new Container(1);
    containers.add(categorySingleItem);
    currentContainerID++;
    // add categories with a random number of items
    for (int a = 0; a < EXTRA_CATEGORIES_TO_GENERATE; a++) {
        containers.add(new Container(1 + (int) Math.floor((size - 1) * Math.random())));
        currentContainerID++;
    }
}

From source file:it.polimi.diceH2020.SPACE4Cloud.shared.solution.SolutionPerJob.java

public void setNumberContainers(int numberContainers) {
    if (this.numberContainers == null || this.numberContainers.intValue() != numberContainers) {
        changed = true;//  w  w  w .  j a v  a 2s  .c  o  m
    }
    this.numberContainers = numberContainers;
    // update num of vm
    if (xi != null) {
        this.numberVM = (int) Math.ceil((double) this.numberContainers / xi);
    } else {
        return;
    }
    if (typeVMselected != null && typeVMselected.getEta() >= 0) {
        this.numSpotVM = (int) Math.floor(typeVMselected.getEta() * this.numberVM);
        this.numReservedVM = (int) Math.min(typeVMselected.getR(), (this.numberVM - numSpotVM));
        this.numOnDemandVM = Math.max(0, this.numberVM - numSpotVM - numReservedVM);
    }
}

From source file:com.joyent.manta.client.crypto.AesCbcCipherDetails.java

/**
 * Calculates the complete number of bytes for content including the hmac or tag if one exists.
 *
 * @param plaintextSize size in bytes of unencrypted body
 * @param blockBytes block size in bytes
 * @param tagOrHmacBytes number of bytes needed for the hmac or authentication tag
 * @param hasIV indicates if the instance has an initialization vector
 * @return calculated byte size of encrypted body with the hmac/authentication tag appended
 *//*from   www  .  ja v  a  2 s . c o m*/
static long calculateContentLength(final long plaintextSize, final int blockBytes, final int tagOrHmacBytes,
        final boolean hasIV) {

    if (plaintextSize <= 0) {
        return (long) blockBytes + tagOrHmacBytes;
    }

    long calculatedContentLength = plaintextSize;
    long padding = 0L;
    if (plaintextSize > blockBytes) {
        padding = plaintextSize % blockBytes;
    } else {
        calculatedContentLength = blockBytes;
    }

    // e.g. content is 20 bytes, block is 16, padding is 4, result = 32
    if (padding > 0) {
        calculatedContentLength = (plaintextSize - padding) + blockBytes;
    }

    // CBC requires an IV an extra block for chaining to work
    if (!hasIV && plaintextSize >= blockBytes) {
        final double blocks = Math.floor(plaintextSize / ((long) blockBytes));
        calculatedContentLength = (((long) blocks + 1) * blockBytes);
    }

    // Append tag or hmac to the end of the stream
    calculatedContentLength += tagOrHmacBytes;

    return calculatedContentLength;
}

From source file:com.surevine.alfresco.audit.MultiReadHttpServletRequestTest.java

byte[] getTestData(int size) {
    byte[] data = new byte[size];

    for (int i = 0; i < size; ++i) {
        data[i] = (byte) Math.floor(Math.random() * 256);
    }/*from www .  jav  a 2 s.  c  o m*/

    return data;
}

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

public double getNormalizedScoreAt(double value) {
    int xstar = Double.valueOf(Math.floor(value + 0.5)).intValue();
    return getNormalizedScoreAt(xstar);
}

From source file:bb.mcmc.analysis.ConvergeStatUtils.java

protected static double quantileType7InR(double[] x, double q) {

    final double[] tempX = x.clone();
    Arrays.sort(tempX);//  w  w  w  .ja v  a2s. co m
    final int n = tempX.length;
    final double index = 1 + (n - 1) * q;
    final double lo = Math.floor(index);
    final double hi = Math.ceil(index);
    Arrays.sort(tempX);
    double qs = tempX[(int) lo - 1];
    final double h = index - lo;
    if (h != 0) {
        qs = (1 - h) * qs + h * tempX[(int) hi - 1];
    }
    return qs;

}