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:beadAnalyzer.DrawPoints.java

public static List<ValuePair<Double, Integer>> binData(final List<Double> data, final double min,
        final double max, final int numBins) {
    // avoid the one value that is exactly 100%
    final double size = max - min + 0.000001;

    // bin and count the entries
    final int[] bins = new int[numBins];

    for (final double v : data)
        ++bins[(int) Math.floor(((v - min) / size) * numBins)];

    // make the list of bins
    final ArrayList<ValuePair<Double, Integer>> hist = new ArrayList<ValuePair<Double, Integer>>();

    final double binSize = size / numBins;
    for (int bin = 0; bin < numBins; ++bin)
        hist.add(new ValuePair<Double, Integer>(min + binSize / 2 + binSize * bin, bins[bin]));

    return hist;//from   w  w w  .ja  va 2  s  .  co m
}

From source file:com.github.tddts.jet.util.Util.java

/**
 * Cut a value to given number of decimals.
 *
 * @param val      number//from  w w w  . ja  v  a2 s.co m
 * @param decimals decimals
 * @return rounded value
 */
public static double roundDown(double val, int decimals) {
    double pow = Math.pow(10, decimals);
    return Math.floor(val * pow) / pow;
}

From source file:io.cloudex.framework.partition.builtin.BinPackingPartition.java

@Override
public List<Partition> partition() {

    Validate.notNull(this.items);

    // sort descending
    Collections.sort(items, Collections.reverseOrder());

    // 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++;
        }// ww  w.j  a  va  2  s.c  om

    } 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 {

        // Mix of First Fit Decreasing (FFD) strategy and Full Bin strategy
        for (int i = 0; i < this.numberOfBins; i++) {
            Partition bin = new Partition();
            bins.add(bin);

            // check if we have ran out of items
            if (!items.isEmpty()) {

                Item largestItem = items.get(0);

                bin.add(largestItem);
                items.remove(largestItem);

                Long currentSum = bin.sum();

                if (currentSum < max) {
                    Long diff = max - currentSum;
                    List<Item> toRemove = new ArrayList<>();

                    for (Item item : items) {
                        //Item item = items.get(j);
                        if (item.getWeight() <= diff) {

                            bin.add(item);
                            toRemove.add(item);

                            if (item.getWeight() == diff) {
                                break;
                            } else {
                                // look for an even small number to fill the gap
                                diff = max - bin.sum();
                            }
                        }
                    }

                    items.removeAll(toRemove);

                }
            }
            bin.calculateScale();
        }

        /*if(!items.isEmpty()) {
        bins.get(bins.size() - 1).addAll(items);
        items.clear();
        }*/

        // 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);

            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++;

            } while (!items.isEmpty());

            items.clear();
        }

    }

    return bins;

}

From source file:com.QuarkLabs.BTCeClient.fragments.HomeFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {

    mTickersContainer = (FixedGridView) getView().findViewById(R.id.tickersContainer);
    mTickersContainer.setExpanded(true);
    final int dashboardSpacing = getResources().getDimensionPixelSize(R.dimen.dashboard_spacing);
    final int dashboardItemSize = getResources().getDimensionPixelSize(R.dimen.dashboard_item_size);
    mTickersContainer.getViewTreeObserver()
            .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override// ww w.  ja va  2s . co m
                public void onGlobalLayout() {
                    if (mTickersDashboardAdapter.getNumColumns() == 0) {
                        final int numColumns = (int) Math
                                .floor(mTickersContainer.getWidth() / (dashboardSpacing + dashboardItemSize));
                        if (numColumns > 0) {
                            mTickersDashboardAdapter.setNumColumns(numColumns);
                            mTickersContainer.setNumColumns(numColumns);
                        }
                    }
                }
            });
    mTickersDashboardAdapter = new TickersDashboardAdapter(getActivity(), this);
    updateStorageWithTickers();
    mTickersDashboardAdapter.update();
    mTickersContainer.setAdapter(mTickersDashboardAdapter);
    TextView emptyView = (TextView) getView().findViewById(R.id.emptyView);
    mTickersContainer.setEmptyView(emptyView);
    mTickersContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return event.getAction() == MotionEvent.ACTION_MOVE;
        }
    });

    //Broadcast receiver initialization
    mGetStatsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (isVisible()) {
                if (mRefreshItem != null) {
                    mRefreshItem.collapseActionView();
                    mRefreshItem.setActionView(null);
                }
                mTickersDashboardAdapter.update();
            }
        }
    };

    LocalBroadcastManager.getInstance(getActivity().getApplicationContext()).registerReceiver(mGetStatsReceiver,
            new IntentFilter("UpdateTickers"));

    //Trade listener, once "Buy" or "Sell" clicked, send the order to server
    View.OnClickListener tradeListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new RegisterTradeRequestTask().execute((v.getId() == R.id.BuyButton) ? "buy" : "sell");
        }
    };

    Button SellButton = (Button) getView().findViewById(R.id.SellButton);
    Button BuyButton = (Button) getView().findViewById(R.id.BuyButton);
    SellButton.setOnClickListener(tradeListener);
    BuyButton.setOnClickListener(tradeListener);

    Button UpdateAccountInfoButton = (Button) getView().findViewById(R.id.UpdateAccountInfoButton);

    UpdateAccountInfoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new UpdateFundsTask().execute();
        }
    });

    //start service to get new data once Dashboard is opened
    getActivity().sendBroadcast(new Intent(getActivity(), StartServiceReceiver.class));
}

From source file:org.openmrs.module.kenyaemr.util.EmrUiUtils.java

/**
 * Formats a regimen in long format//  ww  w .jav a 2s  .c  om
 * @param regimen the regimen
 * @param ui the UI utils
 * @return the string value
 */
public String formatRegimenLong(RegimenOrder regimen, UiUtils ui) {
    if (CollectionUtils.isEmpty(regimen.getDrugOrders())) {
        return "Empty";
    }
    List<String> components = new ArrayList<String>();
    for (DrugOrder o : regimen.getDrugOrders()) {
        StringBuilder sb = new StringBuilder();

        ConceptName cn = o.getConcept().getShortNameInLocale(CoreConstants.LOCALE);
        if (cn == null) {
            cn = o.getConcept().getName(CoreConstants.LOCALE);
        }
        sb.append(cn.getName());

        if (o.getDrug() != null) {
            sb.append(" " + o.getDrug().getDoseStrength() + o.getDrug().getUnits());
        }

        if (o.getDose() != null) {
            // If dose is a whole number, don't format with decimals... e.g. 3.0tabs looks weird
            boolean hasDecimals = Math.floor(o.getDose()) != o.getDose();
            String dose = hasDecimals ? ui.format(o.getDose()) : ui.format(o.getDose().intValue());

            sb.append(" " + dose + o.getUnits());
        }
        if (o.getFrequency() != null) {
            sb.append(" " + o.getFrequency());
        }
        components.add(sb.toString());
    }
    return OpenmrsUtil.join(components, " + ");
}

From source file:com.ibm.mds.MobileServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String question = req.getParameter("questionText");

    if (question == null || question.trim().equals("")) {
        doResp(formartErrJsonMsg(RESP_ERR_COMMAND_NOT_CORRECT, RESP_TXT_COMMAND_NOT_CORRECT), resp);
        return;/*from   ww  w . j  a v  a2  s  . co m*/
    }

    // create the { 'question' : {
    // 'questionText:'...',
    // 'evidenceRequest': { 'items': 5} } json as requested by the service
    JSONObject questionJson = new JSONObject();
    questionJson.put("questionText", question);
    JSONObject evidenceRequest = new JSONObject();
    evidenceRequest.put("items", 5);
    questionJson.put("evidenceRequest", evidenceRequest);

    JSONObject postData = new JSONObject();
    postData.put("question", questionJson);

    try {
        Executor executor = Executor.newInstance().auth(username, password);
        URI serviceURI = new URI(baseURL + "/v1/question/travel").normalize();

        String answersJsonStr = executor
                .execute(Request.Post(serviceURI).addHeader("Accept", "application/json")
                        .addHeader("X-SyncTimeout", "30")
                        .bodyString(postData.toString(), ContentType.APPLICATION_JSON))
                .returnContent().asString();

        JSONObject resultObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        JSONArray pipelines = JSONArray.parse(answersJsonStr);
        // the response has two pipelines, lets use the first one
        JSONObject answersJson = (JSONObject) pipelines.get(0);
        JSONArray answers = (JSONArray) ((JSONObject) answersJson.get("question")).get("evidencelist");

        for (int i = 0; i < answers.size(); i++) {
            JSONObject answer = (JSONObject) answers.get(i);
            double p = Double.parseDouble((String) answer.get("value"));
            p = Math.floor(p * 100);
            JSONObject obj = new JSONObject();
            obj.put("confidence", Double.toString(p) + "%");
            obj.put("text", (String) answer.get("text"));
            jsonArray.add(obj);
        }

        resultObject.put("respCode", RESP_SUCCESS);
        resultObject.put("body", jsonArray);

        doResp(resultObject.toString(), resp);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.sixrr.metrics.ui.charts.DiffHistogramDialog.java

private static boolean isIntegral(double v) {
    if (Math.abs(Math.ceil(v) - v) < EPSILON) {
        return true;
    }// w  w w.jav  a  2 s.  c o  m
    return Math.abs(v - Math.floor(v)) < EPSILON;
}

From source file:org.sirimangalo.meditationplus.AdapterMed.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    View rowView;//from   ww  w.j a  v  a2 s  . c o  m

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(R.layout.list_item_med, parent, false);
    } else {
        rowView = convertView;
    }

    JSONObject p = values.get(position);

    TextView walk = (TextView) rowView.findViewById(R.id.one_walking);
    TextView sit = (TextView) rowView.findViewById(R.id.one_sitting);
    ImageView status = (ImageView) rowView.findViewById(R.id.one_status);
    TextView name = (TextView) rowView.findViewById(R.id.one_med);
    ImageView flag = (ImageView) rowView.findViewById(R.id.one_flag);

    View anuView = rowView.findViewById(R.id.anumodana_shell);
    TextView anuText = (TextView) rowView.findViewById(R.id.anumodana);

    try {
        String wo = p.getString("walking");
        String so = p.getString("sitting");
        int wi = Integer.parseInt(wo);
        int si = Integer.parseInt(so);
        int ti = Integer.parseInt(p.getString("start"));
        int ei = Integer.parseInt(p.getString("end"));

        long nowL = System.currentTimeMillis() / 1000;

        int now = (int) nowL;

        boolean finished = false;

        String ws = "0";
        String ss = "0";

        if (ei > now) {

            float secs = now - ti;

            if (secs > wi * 60 || wi == 0) { //walking done
                float ssecs = (int) (secs - (wi * 60));
                if (ssecs < si * 60) // still sitting
                    ss = Integer.toString((int) Math.floor(si - ssecs / 60));
                status.setImageResource(R.drawable.sitting_icon);
            } else { // still walking
                ws = Integer.toString((int) Math.floor(wi - secs / 60));
                ss = so;
                status.setImageResource(R.drawable.walking_icon);
            }

            ws += "/" + wo;
            ss += "/" + so;
        } else {
            ws = wo;
            ss = so;

            double age = 1 - (now - ei) / MAX_AGE;

            String ageColor = Integer.toHexString((int) (255 * age));

            if (ageColor.length() == 1)
                ageColor = "0" + ageColor;

            int alpha = Color.parseColor("#" + ageColor + "000000");

            walk.setTextColor(alpha);
            sit.setTextColor(alpha);
            name.setTextColor(alpha);
            status.setAlpha((float) age);
            flag.setAlpha((float) age);

        }

        walk.setText(ws);
        sit.setText(ss);

        if (p.has("country")) {
            int id = context.getResources().getIdentifier("flag_" + p.getString("country").toLowerCase(),
                    "drawable", context.getPackageName());
            flag.setImageResource(id);
            flag.setVisibility(View.VISIBLE);
        }

        final String username = p.getString("username");
        final String edit = p.getString("can_edit");
        name.setText(username);

        name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.showProfile(username);
            }
        });

        String type = p.getString("type");
        if ("love".equals(type))
            status.setImageResource(R.drawable.love_icon);

        String anu = p.getString("anumodana");
        if (!anu.equals("0"))
            anuText.setText(anu);

        if (p.getString("anu_me").equals("1")) {
            anuText.setTextColor(0xFF00BB00);
            anuText.setTypeface(null, Typeface.BOLD);
        }

        final String sid = p.getString("sid");

        anuView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "anu clicked");
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                String loggedUsername = prefs.getString("username", "");
                String loginToken = prefs.getString("login_token", "");
                ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                nvp.add(new BasicNameValuePair("form_id", "anumed_" + sid));
                nvp.add(new BasicNameValuePair("login_token", loginToken));
                nvp.add(new BasicNameValuePair("submit", "Refresh"));
                nvp.add(new BasicNameValuePair("username", loggedUsername));
                nvp.add(new BasicNameValuePair("source", "android"));
                PostTaskRunner postTask = new PostTaskRunner(postHandler, context);
                postTask.doPostTask(nvp);

            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    }
    return rowView;
}

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

private XYPlot createPlot(TimeZone timezone, boolean plotPressure) {
    ChartPlotter plotter = null;/*from w ww.  j a  va 2s . c o  m*/
    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:es.udc.gii.common.eaf.algorithm.operator.reproduction.mutation.de.crossover.jade.JADEBinCrossOverScheme.java

@Override
public Individual crossOver(EvolutionaryAlgorithm ea, Individual target, Individual v) {

    Individual trial;/*from  w  ww  . j a va2s  .c o  m*/
    int size, randomI;
    double[] trial_chromosome;
    double cr_i = this.getCRPlugin().get(ea);

    size = target.getChromosomeAt(0).length;
    randomI = (int) Math.floor(EAFRandom.nextDouble() * size);

    trial_chromosome = target.getChromosomeAt(0);
    for (int j = 0; j < size; j++) {

        if (EAFRandom.nextDouble() <= cr_i || randomI == j) {

            trial_chromosome[j] = v.getChromosomeAt(0)[j];

        } else {

            trial_chromosome[j] = target.getChromosomeAt(0)[j];

        }

    }

    JADEIndividual crossoverIndividual = new JADEIndividual();
    crossoverIndividual.setChromosomeAt(0, trial_chromosome);
    crossoverIndividual.setCR(cr_i);
    crossoverIndividual.setF(((JADEIndividual) v).getF());

    return crossoverIndividual;

}