List of usage examples for java.lang Math floor
public static double floor(double a)
From source file:io.cloudex.framework.partition.builtin.BinPackingPartition1.java
@Override public List<Partition> partition() { Validate.notNull(this.items); // sort descending Collections.sort(items, Collections.reverseOrder()); /*long seed = System.nanoTime(); Collections.shuffle(items, new Random(seed));*/ // have we got a maximum set?, otherwise use the size of the largest item Long max = (this.maxBinItems != null) ? this.maxBinItems : items.get(0).getWeight(); PartitionUtils.setScale(items, max); long sum = PartitionUtils.sum(items, max); // check if the number of bins have already been set, in which case we have to fit everything in them if (this.numberOfBins == null) { // lower bound number of bin double numBins = (sum / (float) max); double numWholeBins = Math.floor(numBins); this.numberOfBins = (int) numWholeBins; double excess = numBins - numWholeBins; if (excess > newBinPercentage) { this.numberOfBins++; }// w w w . j a va2s . c o m } else { max = (long) Math.ceil(sum / (float) this.numberOfBins); } List<Partition> bins = new ArrayList<>(); if (this.numberOfBins == 1) { Partition bin = new Partition(); bins.add(bin); bin.addAll(items); items.clear(); } else { // create all the bins for (int i = 0; i < this.numberOfBins; i++) { bins.add(new Partition(max)); } List<Item> toRemove = new ArrayList<>(); int binIndex = 0; for (Item item : items) { // iterate over bins and try to put the item into the first one it fits into Partition startBin = bins.get(binIndex); ; Partition currentBin = null; int count = 0; while (!toRemove.contains(item)) { // did we put the item in a bin? currentBin = bins.get(binIndex); if ((count != 0) && (currentBin == startBin)) { // back where we started item did not fit in last bin. move on break; } if (currentBin.addIfPossible(item)) { // item fit in bin toRemove.add(item); } // try next bin binIndex++; if (binIndex == bins.size()) { // go back to the beginning binIndex = 0; } count++; } } items.removeAll(toRemove); // spread out remaining items, this approximate if (!items.isEmpty()) { //bins.get(bins.size() - 1).addAll(items); //items.clear(); // items are in descending order // sort partitions in ascending order Collections.sort(bins); //Collections.sort(items, Collections.reverseOrder()); Partition smallest; long largestSum = bins.get(bins.size() - 1).sum(); int index = 0; do { smallest = bins.get(index); // spread the remaining items into the bins, largest item into smallest bin for (int i = 0; i < items.size(); i++) { smallest.add(items.remove(i)); if (smallest.sum() > largestSum) { break; } } index++; // there is a large item we can't break if (!items.isEmpty() && (index >= bins.size())) { bins.get(index - 1).addAll(items); items.clear(); } } while (!items.isEmpty()); items.clear(); } for (Partition bin : bins) { bin.calculateScale(); } } return bins; }
From source file:EncodeUtils.java
private static int checkLineLength(byte[] results, int outputIndex) { if (outputIndex == 76 || outputIndex > 76 && (outputIndex - 2 * Math.floor(outputIndex / 76f - 1)) % 76 == 0) { results[outputIndex++] = '\r'; results[outputIndex++] = '\n'; }//from w w w .ja va 2s.c o m return outputIndex; }
From source file:ke.co.tawi.babblesms.server.persistence.utils.ContactGroupUtil.java
/** * Assigns groups to contacts//from w ww. ja v a 2 s . c o m * */ public void putContactsIntoGroups() { List<Contact> contactList = new LinkedList<>(); List<Group> groupList = new LinkedList<>(); // get all the accounts // get all contactgroup uuids for this account List<String> uuids = new LinkedList<>(); try (Connection conn = dbCredentials.getConnection(); PreparedStatement pstmt = conn.prepareStatement("SELECT uuid FROM contactgroup;");) { ResultSet rset = pstmt.executeQuery(); while (rset.next()) { uuids.add(rset.getString("uuid")); } } catch (SQLException e) { logger.error("SQLException when getting uuids of contactcontactgroup."); logger.error(ExceptionUtils.getStackTrace(e)); } // insert new associations in contactgroup table try (Connection conn = dbCredentials.getConnection(); PreparedStatement pstmt = conn.prepareStatement("INSERT INTO contactgroup " + "(uuid, contactuuid, groupuuid, accountuuid) VALUES (?,?,?,?);");) { groupList = groupDAO.getGroups(account); contactList = contactDAO.getContacts(account); // distribute contacts into groups in the ratio 7:2:1 int contactListSize = contactList.size(); // first portion of the ratio int firstPortion = (int) Math.floor(contactListSize * 0.7);// 7/10 for (int i = 0; i < firstPortion; i++) { pstmt.setString(1, UUID.randomUUID().toString()); pstmt.setString(2, contactList.get(i).getUuid()); pstmt.setString(3, groupList.get(3).getUuid()); pstmt.setString(4, account.getUuid()); pstmt.executeUpdate(); } // second portion of the ratio int secondPortion = firstPortion + (int) Math.floor(contactListSize * 0.2);// 2/10 for (int i = firstPortion; i < secondPortion; i++) { pstmt.setString(1, UUID.randomUUID().toString()); pstmt.setString(2, contactList.get(i).getUuid()); pstmt.setString(3, groupList.get(2).getUuid()); pstmt.setString(4, account.getUuid()); pstmt.executeUpdate(); } // third portion of the ratio for (int i = secondPortion; i < contactListSize; i++) { pstmt.setString(1, UUID.randomUUID().toString()); pstmt.setString(2, contactList.get(i).getUuid()); pstmt.setString(3, groupList.get(0).getUuid()); pstmt.setString(4, account.getUuid()); pstmt.executeUpdate(); } // put some contacts from one group into another group for (int i = firstPortion; i < secondPortion; i++) { pstmt.setString(1, UUID.randomUUID().toString()); pstmt.setString(2, contactList.get(i).getUuid()); pstmt.setString(3, groupList.get(0).getUuid()); pstmt.setString(4, account.getUuid()); pstmt.executeUpdate(); if (i == (secondPortion - 5)) break; } // put from contacts from one group into another group for (int i = secondPortion + 5; i < contactListSize; i++) { pstmt.setString(1, UUID.randomUUID().toString()); pstmt.setString(2, contactList.get(i).getUuid()); pstmt.setString(3, groupList.get(2).getUuid()); pstmt.setString(4, account.getUuid()); pstmt.executeUpdate(); if (i == 20) break; } } catch (SQLException e) { logger.error("SQLException while inserting new association in contactgroup table"); logger.error(ExceptionUtils.getStackTrace(e)); } }
From source file:mase.me.MESubpopulation.java
protected int[] discretise(double[] v) { int[] r = new int[v.length]; for (int i = 0; i < v.length; i++) { r[i] = (int) Math.floor(v[i] / resolution); }/* w w w .ja v a 2 s . c om*/ return r; }
From source file:com.hmsinc.epicenter.webapp.chart.SNColumnArrangement.java
/** * Calculates and sets the bounds of all the items in the specified * container, subject to the given constraint. The <code>Graphics2D</code> * can be used by some items (particularly items containing text) to * calculate sizing parameters.//from www . j a va2s . c om * * @param container * the container whose items are being arranged. * @param g2 * the graphics device. * @param constraint * the size constraint. * * @return The size of the container after arrangement of the contents. */ @SuppressWarnings("unchecked") public Size2D arrange(BlockContainer container, Graphics2D g2, RectangleConstraint constraint) { List<Block> blocks = container.getBlocks(); // calculate max width of entries double maxWidth = 0.0; double maxHeight = 0.0; for (Block block : blocks) { Size2D size = block.arrange(g2, RectangleConstraint.NONE); maxWidth = Math.max(maxWidth, size.width + this.horizontalGap); maxHeight = Math.max(maxHeight, size.height + this.verticalGap); } // calculate number of columns double width = 0.0; if (constraint.getWidthConstraintType() == LengthConstraintType.FIXED) { width = constraint.getWidth(); } else if (constraint.getWidthConstraintType() == LengthConstraintType.RANGE) { Range range = constraint.getWidthRange(); width = range.getUpperBound(); } else { throw new RuntimeException("Not implemented."); } int columns = (int) (Math.floor(width / maxWidth)); if (columns > 0) { columns--; } // for all columns int colx = -1; int coly = 0; for (Block block : blocks) { Size2D size = block.arrange(g2, RectangleConstraint.NONE); if (colx < columns) { colx++; } else { colx = 0; coly++; } double x = colx * maxWidth; double y = coly * maxHeight; block.setBounds(new Rectangle2D.Double(x, y, size.width, size.height)); } // calculate size of bounding double bWidth = (coly == 0) ? (colx + 1) * maxWidth : (columns + 1) * maxWidth; double bHeight = (coly + 1) * maxHeight; return new Size2D(bWidth, bHeight); }
From source file:MSUmpire.LCMSPeakStructure.LCMSPeakDIAMS2.java
public LCMSPeakDIAMS2(String Filename, DIAPack parentDIA, InstrumentParameter parameter, XYData WindowMZ, XYData LastWindowMZ, SpectrumParserBase spectrumparser, int NoCPUs) { this.DIA_MZ_Range = WindowMZ; this.Last_MZ_Range = LastWindowMZ; this.WindowID = (int) Math.floor(WindowMZ.getX()) + "_" + (int) Math.floor(WindowMZ.getY()); this.SpectrumParser = spectrumparser; this.ScanCollectionName = FilenameUtils.getFullPath(Filename) + "/" + FilenameUtils.getBaseName(Filename) + "_" + (int) Math.floor(WindowMZ.getX()) + "_" + (int) Math.floor(WindowMZ.getY()); this.ParentmzXMLName = FilenameUtils.getFullPath(Filename) + "/" + FilenameUtils.getBaseName(Filename); this.parentDIA = parentDIA; this.parameter = parameter; this.MaxNoPeakCluster = parameter.MaxMS2NoPeakCluster; this.MinNoPeakCluster = parameter.MinMS2NoPeakCluster; this.StartCharge = parameter.MS2StartCharge; this.EndCharge = parameter.MS2EndCharge; this.MiniIntensity = parameter.MinMSMSIntensity; this.SNR = parameter.MS2SNThreshold; this.NoCPUs = NoCPUs; }
From source file:com.itemanalysis.psychometrics.scaling.PercentileRank.java
/** * Creates a TreeMap<Integer, Double> lookup table of percentile ranks. * The key is a score level and the rho is a percentile rank. This * method is useful when finding percentile ranks that correspond to an examinee's * raw score. After calling this method, individual elements in the * TreeMap can be accessed with getPercentileRankAt(int rho) or * valueIterator()./*from ww w . ja va2 s.co m*/ * */ public void createLookupTable() { prankTable = new TreeMap<Integer, Double>(); Iterator<Comparable<?>> iter = freqTable.valuesIterator(); int index = 0; int length = freqTable.getUniqueCount(); double[] xval = new double[length + 2]; double[] yval = new double[length + 2]; int x = 0; int xstar = 0; //create boundaries below the minimum possible test score //and above teh maximum possible test score. //This change allows for the interpolation of percentile //ranks at the min and max possible test score. xval[0] = min - .5; yval[0] = 0; xval[length + 1] = (double) max + 0.5; yval[length + 1] = 100; index = 1; //compute percentile ranks fro observed scores while (iter.hasNext()) { x = ((Long) iter.next()).intValue(); xstar = Double.valueOf(Math.floor(x + 0.5)).intValue(); xval[index] = Double.valueOf(xstar); yval[index] = Double.valueOf(percentileRank(x, xstar)); index++; } //interpolate values LinearInterpolator interpolator = new LinearInterpolator(); PolynomialSplineFunction splineFunction = interpolator.interpolate(xval, yval); //create lookup table with interpolated values x = min; double y = 0.0; while (x <= max) { y = splineFunction.value(x); prankTable.put(x, y); x += 1; } }
From source file:io.v.android.apps.syncslides.DeckChooserFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_deck_chooser, container, false); FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.new_deck_fab); fab.setOnClickListener(new View.OnClickListener() { @Override//www. j a va 2 s. co m public void onClick(View v) { onImportDeck(); } }); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.deck_grid); mRecyclerView.setHasFixedSize(true); // Statically set the span count (i.e. number of columns) for now... See below. mLayoutManager = new GridLayoutManager(getContext(), 2); mRecyclerView.setLayoutManager(mLayoutManager); // Dynamically set the span based on the screen width. Cribbed from // http://stackoverflow.com/questions/26666143/recyclerview-gridlayoutmanager-how-to-auto-detect-span-count mRecyclerView.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this); int viewWidth = mRecyclerView.getMeasuredWidth(); float cardViewWidth = getActivity().getResources().getDimension(R.dimen.deck_card_width); int newSpanCount = (int) Math.floor(viewWidth / cardViewWidth); mLayoutManager.setSpanCount(newSpanCount); mLayoutManager.requestLayout(); } }); return rootView; }
From source file:Main.java
private static int computeInitialSampleSize(Options options, int minSideLength, int maxNumOfPixels) { double w = options.outWidth; double h = options.outHeight; int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); int upperBound = (minSideLength == UNCONSTRAINED) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength)); if (upperBound < lowerBound) { // return the larger one when there is no overlapping zone. return lowerBound; }/*from w ww. j av a 2s .c o m*/ if ((maxNumOfPixels == UNCONSTRAINED) && (minSideLength == UNCONSTRAINED)) { return 1; } else if (minSideLength == UNCONSTRAINED) { return lowerBound; } else { return upperBound; } }
From source file:cz.alej.michalik.totp.util.TOTP.java
/** * Vrt TOTP heslo pro aktuln ?as/*ww w. j av a 2 s . c om*/ * * @return TOTP heslo jako int */ public int get() { long now = System.currentTimeMillis() / 1000; hotp.setCounter((int) Math.floor((now - t0) / step)); return hotp.get(); }