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:com.google.blockly.model.FieldNumber.java

/**
 * Sets the constraints on valid number values.
 * <p/>/*from  w w w. j av a2s .co  m*/
 * Changing the constraints may trigger a {@link ChangeEvent}, even if the value does not
 * change.
 *
 * @param min The minimum allowed value, inclusive.
 * @param max The maximum allowed value, inclusive.
 * @param precision The precision of allowed values. Valid values are multiples of this number,
 *                  such as 1, 0.1, 100, or 0.125.
 */
public void setConstraints(double min, double max, double precision) {
    if (max == Double.POSITIVE_INFINITY || Double.isNaN(max)) {
        max = NO_CONSTRAINT;
    } else if (max == Double.NEGATIVE_INFINITY) {
        throw new IllegalArgumentException("Max cannot be -Inf. No valid values would exist.");
    }
    if (min == Double.NEGATIVE_INFINITY || Double.isNaN(min)) {
        min = NO_CONSTRAINT;
    } else if (min == Double.POSITIVE_INFINITY) {
        throw new IllegalArgumentException("Min cannot be Inf. No valid values would exist.");
    }
    if (precision == 0 || Double.isNaN(precision)) {
        precision = NO_CONSTRAINT;
    }
    if (Double.isInfinite(precision)) {
        throw new IllegalArgumentException("Precision cannot be infinite.");
    }
    if (!Double.isNaN(min) && !Double.isNaN(max) && min > max) {
        throw new IllegalArgumentException("Minimum value must be less than max. Found " + min + " > " + max);
    }
    if (!Double.isNaN(precision) && precision <= 0) {
        throw new IllegalArgumentException("Precision must be positive. Found " + precision);
    }

    double effectiveMin = Double.isNaN(min) ? -Double.MAX_VALUE : min;
    double effectiveMax = Double.isNaN(max) ? Double.MAX_VALUE : max;
    if (!Double.isNaN(precision)) {
        if (effectiveMin < 0) {
            double multiplier = Math.floor(-effectiveMin / precision);
            effectiveMin = precision * -multiplier;
        } else {
            double multiplier = Math.ceil(effectiveMin / precision);
            effectiveMin = precision * multiplier;
        }
        if (effectiveMax < 0) {
            double multiplier = Math.ceil(-effectiveMax / precision);
            effectiveMax = precision * -multiplier;
        } else {
            double multiplier = Math.floor(effectiveMax / precision);
            effectiveMax = precision * multiplier;

        }
        if (effectiveMin > effectiveMax) {
            throw new IllegalArgumentException("No valid value in range.");
        }
    }

    mMin = min;
    mMax = max;
    mPrecision = precision;
    mEffectiveMin = effectiveMin;
    mEffectiveMax = effectiveMax;
    mIntegerPrecision = (precision == Math.round(precision));
    if (!hasPrecision()) {
        mFormatter = NAIVE_DECIMAL_FORMAT;
    } else if (mIntegerPrecision) {
        mFormatter = INTEGER_DECIMAL_FORMAT;
    } else {
        String precisionStr = NAIVE_DECIMAL_FORMAT.format(precision);
        int decimalChar = precisionStr.indexOf('.');
        if (decimalChar == -1) {
            mFormatter = INTEGER_DECIMAL_FORMAT;
        } else {
            int significantDigits = precisionStr.length() - decimalChar;
            StringBuilder sb = new StringBuilder("0.");
            char[] sigDigitsFormat = new char[significantDigits];
            Arrays.fill(sigDigitsFormat, '#');
            sb.append(sigDigitsFormat);
            mFormatter = new DecimalFormat(sb.toString());
        }
    }

    setValueImpl(mValue, true);
}

From source file:com.miz.mizuu.fragments.MovieDiscoveryFragment.java

@Override
public void onViewCreated(View v, Bundle savedInstanceState) {
    super.onViewCreated(v, savedInstanceState);

    mProgressBar = (ProgressBar) v.findViewById(R.id.progress);
    mProgressBar.setVisibility(View.GONE);

    mAdapter = new ImageAdapter(getActivity());

    mGridView = (ObservableGridView) v.findViewById(R.id.gridView);
    mGridView.setAdapter(mAdapter);/*from   w  ww . ja  v a2  s.  c  o  m*/
    mGridView.setColumnWidth(mImageThumbSize);

    // Calculate the total column width to set item heights by factor 1.5
    mGridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (mAdapter.getNumColumns() == 0) {
                final int numColumns = (int) Math
                        .floor(mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing));
                if (numColumns > 0)
                    mAdapter.setNumColumns(numColumns);

                MizLib.removeViewTreeObserver(mGridView.getViewTreeObserver(), this);
            }
        }
    });
    mGridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            Intent i = new Intent();

            if (mMovieMap.get(Integer.valueOf(mMovies.get(arg2).getId()))) {
                i.setClass(getActivity(), MovieDetails.class);
                i.putExtra("tmdbId", mMovies.get(arg2).getId());
            } else {
                i.setClass(getActivity(), TMDbMovieDetails.class);
                i.putExtra("tmdbId", mMovies.get(arg2).getId());
                i.putExtra("title", mMovies.get(arg2).getTitle());
            }

            ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),
                    arg1.findViewById(R.id.cover), "cover");
            ActivityCompat.startActivity(getActivity(), i, options.toBundle());
        }
    });

    if (getArguments().containsKey("json")) {
        mJson = getArguments().getString("json");
        mBaseUrl = getArguments().getString("baseUrl");
        loadJson();
    }

}

From source file:Float11.java

static public double pow(double x, double y) {
    if (y == 0.)//from  w w w  . j  av  a2  s . c om
        return 1.;
    if (y == 1.)
        return x;
    if (x == 0.)
        return 0.;
    if (x == 1.)
        return 1.;
    //
    long l = (long) Math.floor(y);
    boolean integerValue = (y == (double) l);
    //
    if (integerValue) {
        boolean neg = false;
        if (y < 0.)
            neg = true;
        //
        double result = x;
        for (long i = 1; i < (neg ? -l : l); i++)
            result = result * x;
        //
        if (neg)
            return 1. / result;
        else
            return result;
    } else {
        if (x > 0.)
            return exp(y * log(x));
        else
            return Double.NaN;
    }
}

From source file:com.cloudera.knittingboar.records.TestTwentyNewsgroupsCustomRecordParseOLRRun.java

@Test
public void testRecordFactoryOnDatasetShard() throws Exception {
    // TODO a test with assertions is not a test
    // p.270 ----- metrics to track lucene's parsing mechanics, progress,
    // performance of OLR ------------
    double averageLL = 0.0;
    double averageCorrect = 0.0;
    int k = 0;//from   w  w  w.j  av  a 2s .com
    double step = 0.0;
    int[] bumps = new int[] { 1, 2, 5 };

    TwentyNewsgroupsRecordFactory rec_factory = new TwentyNewsgroupsRecordFactory("\t");
    // rec_factory.setClassSplitString("\t");

    JobConf job = new JobConf(defaultConf);

    long block_size = localFs.getDefaultBlockSize(workDir);

    LOG.info("default block size: " + (block_size / 1024 / 1024) + "MB");

    // matches the OLR setup on p.269 ---------------
    // stepOffset, decay, and alpha --- describe how the learning rate decreases
    // lambda: amount of regularization
    // learningRate: amount of initial learning rate
    @SuppressWarnings("resource")
    OnlineLogisticRegression learningAlgorithm = new OnlineLogisticRegression(20, FEATURES, new L1()).alpha(1)
            .stepOffset(1000).decayExponent(0.9).lambda(3.0e-5).learningRate(20);

    FileInputFormat.setInputPaths(job, workDir);

    // try splitting the file in a variety of sizes
    TextInputFormat format = new TextInputFormat();
    format.configure(job);
    Text value = new Text();

    int numSplits = 1;

    InputSplit[] splits = format.getSplits(job, numSplits);

    LOG.info("requested " + numSplits + " splits, splitting: got =        " + splits.length);
    LOG.info("---- debug splits --------- ");
    rec_factory.Debug();
    int total_read = 0;

    for (int x = 0; x < splits.length; x++) {

        LOG.info("> Split [" + x + "]: " + splits[x].getLength());

        int count = 0;
        InputRecordsSplit custom_reader = new InputRecordsSplit(job, splits[x]);
        while (custom_reader.next(value)) {
            Vector v = new RandomAccessSparseVector(TwentyNewsgroupsRecordFactory.FEATURES);
            int actual = rec_factory.processLine(value.toString(), v);

            String ng = rec_factory.GetNewsgroupNameByID(actual);

            // calc stats ---------

            double mu = Math.min(k + 1, 200);
            double ll = learningAlgorithm.logLikelihood(actual, v);
            averageLL = averageLL + (ll - averageLL) / mu;

            Vector p = new DenseVector(20);
            learningAlgorithm.classifyFull(p, v);
            int estimated = p.maxValueIndex();

            int correct = (estimated == actual ? 1 : 0);
            averageCorrect = averageCorrect + (correct - averageCorrect) / mu;
            learningAlgorithm.train(actual, v);
            k++;
            int bump = bumps[(int) Math.floor(step) % bumps.length];
            int scale = (int) Math.pow(10, Math.floor(step / bumps.length));

            if (k % (bump * scale) == 0) {
                step += 0.25;
                LOG.info(String.format("%10d %10.3f %10.3f %10.2f %s %s", k, ll, averageLL,
                        averageCorrect * 100, ng, rec_factory.GetNewsgroupNameByID(estimated)));
            }

            learningAlgorithm.close();
            count++;
        }

        LOG.info("read: " + count + " records for split " + x);
        total_read += count;
    } // for each split
    LOG.info("total read across all splits: " + total_read);
    rec_factory.Debug();
}

From source file:org.apache.drill.exec.store.mpjdbc.MPJdbcGroupScan.java

@Override
public void applyAssignments(List<DrillbitEndpoint> incomingEndpoints) {
    final int numSlots = incomingEndpoints.size();
    int totalAssignmentsTobeDone = 1;
    Preconditions.checkArgument(numSlots <= totalAssignmentsTobeDone, String.format(
            "Incoming endpoints %d is greater than number of chunks %d", numSlots, totalAssignmentsTobeDone));
    final int minPerEndpointSlot = (int) Math.floor((double) totalAssignmentsTobeDone / numSlots);
    final int maxPerEndpointSlot = (int) Math.ceil((double) totalAssignmentsTobeDone / numSlots);
    /* Map for (index,endpoint)'s */
    endpointFragmentMapping = Maps.newHashMapWithExpectedSize(numSlots);
    /* Reverse mapping for above indexes */
    Map<String, Queue<Integer>> endpointHostIndexListMap = Maps.newHashMap();
    /*//w  w w  .  j ava  2 s .c o  m
     * Initialize these two maps
     */
    for (int i = 0; i < numSlots; ++i) {
        List<MPJdbcScanSpec> val = new ArrayList<MPJdbcScanSpec>(maxPerEndpointSlot);
        val.add(this.mPJdbcScanSpec);
        endpointFragmentMapping.put(i, val);
        String hostname = incomingEndpoints.get(i).getAddress();
        Queue<Integer> hostIndexQueue = endpointHostIndexListMap.get(hostname);
        if (hostIndexQueue == null) {
            hostIndexQueue = Lists.newLinkedList();
            endpointHostIndexListMap.put(hostname, hostIndexQueue);
        }
        hostIndexQueue.add(i);
    }
}

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

@Override
public int overlapPartition(Shape shape) {
    if (shape == null)
        return -1;
    Rectangle shapeMBR = shape.getMBR();
    if (shapeMBR == null)
        return -1;
    Point centerPoint = shapeMBR.getCenterPoint();
    int col = (int) Math.floor((centerPoint.x - x) / tileWidth);
    int row = (int) Math.floor((centerPoint.y - y) / tileHeight);
    return getCellNumber(col, row);
}

From source file:com.nextgis.firereporter.ScanexNotificationItem.java

/**
 * Formats coordinate value to string based on output type (modified version
 * from Android API)//from  ww  w .j  a  v a 2  s .c o  m
 */
public static String formatCoord(double coordinate, int outputType) {

    StringBuilder sb = new StringBuilder();
    char endChar = DEGREE_CHAR;

    DecimalFormat df = new DecimalFormat("###.######");
    if (outputType == Location.FORMAT_MINUTES || outputType == Location.FORMAT_SECONDS) {

        df = new DecimalFormat("##.###");

        int degrees = (int) Math.floor(coordinate);
        sb.append(degrees);
        sb.append(DEGREE_CHAR); // degrees sign
        endChar = '\''; // minutes sign
        coordinate -= degrees;
        coordinate *= 60.0;

        if (outputType == Location.FORMAT_SECONDS) {

            df = new DecimalFormat("##.##");

            int minutes = (int) Math.floor(coordinate);
            sb.append(minutes);
            sb.append('\''); // minutes sign
            endChar = '\"'; // seconds sign
            coordinate -= minutes;
            coordinate *= 60.0;
        }
    }

    sb.append(df.format(coordinate));
    sb.append(endChar);

    return sb.toString();
}

From source file:org.matsim.contrib.dvrp.util.chart.ScheduleChartUtils.java

private static <T extends Task> TaskSeriesCollection createScheduleDataset(List<? extends Vehicle> vehicles,
        DescriptionCreator<T> descriptionCreator) {
    TaskSeriesCollection collection = new TaskSeriesCollection();

    for (Vehicle v : vehicles) {
        @SuppressWarnings("unchecked")
        Schedule<T> schedule = (Schedule<T>) v.getSchedule();

        final TaskSeries scheduleTaskSeries = new TaskSeries(v.getId().toString());

        if (schedule.getStatus() == ScheduleStatus.UNPLANNED) {
            collection.add(scheduleTaskSeries);
            continue;
        }/*w ww .j  av  a2 s  .  co m*/

        List<T> tasks = schedule.getTasks();

        for (T t : tasks) {
            String description = descriptionCreator.create(t);

            TimePeriod duration = new SimpleTimePeriod(//
                    new Date((int) Math.floor(t.getBeginTime() * 1000)), //
                    new Date((int) Math.ceil(t.getEndTime() * 1000)));

            scheduleTaskSeries.add(new ChartTask<T>(description, duration, t));
        }

        collection.add(scheduleTaskSeries);
    }

    return collection;
}

From source file:com.alibaba.simpleimage.util.ImageUtils.java

public static final int clampRoundInt(double in) {
    return (in > Integer.MAX_VALUE ? Integer.MAX_VALUE
            : (in >= Integer.MIN_VALUE ? (int) Math.floor(in + 0.5) : Integer.MIN_VALUE));
}

From source file:com.ibm.bi.dml.runtime.matrix.data.LibMatrixDatagen.java

/**
 * /*from  www  .j a v a2s. c  o m*/
 * @param nrow
 * @param ncol
 * @param brlen
 * @param bclen
 * @param sparsity
 * @return
 * @throws DMLRuntimeException
 */
public static long[] computeNNZperBlock(long nrow, long ncol, int brlen, int bclen, double sparsity)
        throws DMLRuntimeException {
    int numBlocks = (int) (Math.ceil((double) nrow / brlen) * Math.ceil((double) ncol / bclen));
    //System.out.println("nrow=" + nrow + ", brlen=" + brlen + ", ncol="+ncol+", bclen=" + bclen + "::: " + Math.ceil(nrow/brlen));

    // CURRENT: 
    //       Total #of NNZ is set to the expected value (nrow*ncol*sparsity).
    // TODO: 
    //      Instead of using the expected value, one should actually 
    //       treat NNZ as a random variable and accordingly generate a random value.
    long nnz = (long) Math.ceil(nrow * (ncol * sparsity));
    //System.out.println("Number of blocks = " + numBlocks + "; NNZ = " + nnz);

    if (numBlocks > Integer.MAX_VALUE) {
        throw new DMLRuntimeException(
                "A random matrix of size [" + nrow + "," + ncol + "] can not be created. Number of blocks ("
                        + numBlocks + ") exceeds the maximum integer size. Try to increase the block size.");
    }

    // Compute block-level NNZ
    long[] ret = new long[numBlocks];
    Arrays.fill(ret, 0);

    if (nnz < numBlocks) {
        // Ultra-sparse matrix

        // generate the number of blocks with at least one non-zero
        // = a random number between [1,nnz]
        Random runif = new Random(System.nanoTime());
        int numNZBlocks = 1;
        if (nnz - 1 > 0)
            numNZBlocks += runif.nextInt((int) (nnz - 1)); // To avoid exception from random.nextInt(0) 

        // distribute non-zeros across numNZBlocks

        // compute proportions for each nzblock 
        // - divide (0,1] interval into numNZBlocks portions of random size
        double[] blockNNZproportions = new double[numNZBlocks];

        runif.setSeed(System.nanoTime());
        for (int i = 0; i < numNZBlocks - 1; i++) {
            blockNNZproportions[i] = runif.nextDouble();
        }
        blockNNZproportions[numNZBlocks - 1] = 1;
        // sort the values in ascending order
        Arrays.sort(blockNNZproportions);

        // compute actual number of non zeros per block according to proportions
        long actualnnz = 0;
        int bid;
        runif.setSeed(System.nanoTime());
        for (int i = 0; i < numNZBlocks; i++) {
            bid = -1;
            do {
                bid = runif.nextInt(numBlocks);
            } while (ret[bid] != 0);

            double prop = (i == 0 ? blockNNZproportions[i]
                    : (blockNNZproportions[i] - blockNNZproportions[i - 1]));
            ret[bid] = (long) Math.floor(prop * nnz);
            actualnnz += ret[bid];
        }

        // Code to make sure exact number of non-zeros are generated
        while (actualnnz < nnz) {
            bid = runif.nextInt(numBlocks);
            ret[bid]++;
            actualnnz++;
        }
    } else {
        int bid = 0;

        //long actualnnz = 0;
        for (long r = 0; r < nrow; r += brlen) {
            long curBlockRowSize = Math.min(brlen, (nrow - r));
            for (long c = 0; c < ncol; c += bclen) {
                long curBlockColSize = Math.min(bclen, (ncol - c));
                ret[bid] = (long) (curBlockRowSize * curBlockColSize * sparsity);
                //actualnnz += ret[bid];
                bid++;
            }
        }
    }
    return ret;
}