List of usage examples for java.lang Math floor
public static double floor(double a)
From source file:geogebra.util.MyMath.java
/** * Factorial function of x. If x is an integer value x! is returned, * otherwise gamma(x + 1) will be returned. For x < 0 Double.NaN is * returned.//from ww w . ja v a 2 s . c om * @param x * @return factorial */ final public static double factorial(double x) { if (x < 0) return Double.NaN; // bugfix Michael Borcherds 2008-05-04 // big x or floating point x is computed using gamma function if (x < 0 || x > 32 || x - Math.floor(x) > 1E-10) // exp of log(gamma(x+1)) return Math.exp(Gamma.logGamma(x + 1.0)); int n = (int) x; int j; while (factorialTop < n) { j = factorialTop++; factorialTable[factorialTop] = factorialTable[j] * factorialTop; } return factorialTable[n]; }
From source file:io.v.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(v -> onImportDeck()); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.deck_grid); // The cards for the decks are always the same size. 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()// w w w . j a v a 2s .c om .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(); } }); mAdapter = new DeckListAdapter(DB.Singleton.get(), new RpcPresentationDiscovery(V23.Singleton.get().getVContext())); return rootView; }
From source file:net.groupbuy.template.directive.PaginationDirective.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { String pattern = FreemarkerUtils.getParameter(PATTERN_PARAMETER_NAME, String.class, params); Integer pageNumber = FreemarkerUtils.getParameter(PAGE_NUMBER_PARAMETER_NAME, Integer.class, params); Integer totalPages = FreemarkerUtils.getParameter(TOTAL_PAGES_PARAMETER_NAME, Integer.class, params); Integer segmentCount = FreemarkerUtils.getParameter(SEGMENT_COUNT_PARAMETER_NAME, Integer.class, params); if (pageNumber == null || pageNumber < 1) { pageNumber = 1;//from w w w. j a v a2 s . c o m } if (totalPages == null || totalPages < 1) { totalPages = 1; } if (segmentCount == null || segmentCount < 1) { segmentCount = 5; } boolean hasPrevious = pageNumber > 1; boolean hasNext = pageNumber < totalPages; boolean isFirst = pageNumber == 1; boolean isLast = pageNumber.equals(totalPages); int previousPageNumber = pageNumber - 1; int nextPageNumber = pageNumber + 1; int firstPageNumber = 1; int lastPageNumber = totalPages; int startSegmentPageNumber = pageNumber - (int) Math.floor((segmentCount - 1) / 2D); int endSegmentPageNumber = pageNumber + (int) Math.ceil((segmentCount - 1) / 2D); if (startSegmentPageNumber < 1) { startSegmentPageNumber = 1; } if (endSegmentPageNumber > totalPages) { endSegmentPageNumber = totalPages; } List<Integer> segment = new ArrayList<Integer>(); for (int i = startSegmentPageNumber; i <= endSegmentPageNumber; i++) { segment.add(i); } Map<String, Object> variables = new HashMap<String, Object>(); variables.put(PATTERN_VARIABLE_NAME, pattern); variables.put(PAGE_NUMBER_VARIABLE_NAME, pageNumber); variables.put(PAGE_COUNT_VARIABLE_NAME, totalPages); variables.put(SEGMENT_COUNT_VARIABLE_NAME, segmentCount); variables.put(HAS_PREVIOUS_VARIABLE_NAME, hasPrevious); variables.put(HAS_NEXT_VARIABLE_NAME, hasNext); variables.put(IS_FIRST_VARIABLE_NAME, isFirst); variables.put(IS_LAST_VARIABLE_NAME, isLast); variables.put(PREVIOUS_PAGE_NUMBER_VARIABLE_NAME, previousPageNumber); variables.put(NEXT_PAGE_NUMBER_VARIABLE_NAME, nextPageNumber); variables.put(FIRST_PAGE_NUMBER_VARIABLE_NAME, firstPageNumber); variables.put(LAST_PAGE_NUMBER_VARIABLE_NAME, lastPageNumber); variables.put(SEGMENT_VARIABLE_NAME, segment); setLocalVariables(variables, env, body); }
From source file:com.garyclayburg.UserRestSmokeTest.java
@Ignore @Test//ww w . j a v a 2s . c om public void testJsonApache() throws Exception { RestTemplate rest = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); SimpleUser user1 = new SimpleUser(); user1.setFirstname("Tommy"); user1.setLastname("Deleteme"); user1.setId("112" + (int) (Math.floor(Math.random() * 10000))); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Content-Type", "application/json"); // HttpEntity<?> requestEntity = new HttpEntity(requestHeaders); HttpEntity<?> requestEntity = new HttpEntity(user1, requestHeaders); ResponseEntity<SimpleUser> simpleUserResponseEntity = rest.exchange( "http://" + endpoint + "/audited-users/auditedsave", HttpMethod.POST, requestEntity, SimpleUser.class); // ResponseEntity<SimpleUser> userResponseEntity = // rest.postForEntity("http://" + endpoint + "/audited-users/auditedsave",user1,SimpleUser.class); log.info("got a response"); MatcherAssertionErrors.assertThat(simpleUserResponseEntity.getStatusCode(), Matchers.equalTo(HttpStatus.OK)); }
From source file:imagingbook.lib.math.Matrix.java
public static int[] floor(double[] A) { int[] B = new int[A.length]; for (int i = 0; i < A.length; i++) { B[i] = (int) Math.floor(A[i]); }/*from www . j a va 2s . c o m*/ return B; }
From source file:no.met.jtimeseries.marinogram.MarinogramWavePlot.java
private XYPlot createPlot(TimeZone timezone, boolean plotWaveDirection, boolean plotWaveHeight) { ChartPlotter plotter = new ChartPlotter(); // default setting plotter.setHeight(this.getHeight()); plotter.setWidth(this.getWidth()); plotter.setPlotDefaultProperties("", ""); Color waveHeightColor = new Color(0, 105, 161); Color waveDirectionColor = new Color(0, 105, 161); // plot style PlotStyle.Builder waveStyleBuilder = new PlotStyle.Builder("Wave"); PlotStyle plotStyle;/*from w w w . j ava2 s . co m*/ NumberPhenomenon waveDirection = getOceanForecastDataModel() .getPhenomenen(PhenomenonName.WaveDirection.toString(), NumberPhenomenon.class); NumberPhenomenon waveHeight = getOceanForecastDataModel() .getPhenomenen(PhenomenonName.WaveHeight.toString(), NumberPhenomenon.class); if (waveHeight == null || waveDirection == null) { return null; } double tick = (waveHeight.getMaxValue() - waveHeight.getMinValue()) / 2; tick = Math.ceil(tick); double lowBound = Math.floor(waveHeight.getMinValue() / (tick)) * (tick); //The minimum scale is 0 lowBound = lowBound < 0 ? 0 : lowBound; lowBound = lowBound - tick / 2; double upperBound = lowBound + tick * 4; // reference the range axis NumberAxis leftNumberAxis = new NumberAxis(); leftNumberAxis.setLabel(messages.getString("parameter.wave") + " (m)"); leftNumberAxis.setLabelPaint(waveHeightColor); leftNumberAxis.setTickLabelPaint(waveHeightColor); leftNumberAxis.setLowerBound(lowBound); leftNumberAxis.setUpperBound(upperBound); leftNumberAxis.setTickUnit(new NumberTickUnit(tick)); NumberAxis rightNumberAxis = new NumberAxis(); rightNumberAxis.setLabelPaint(waveHeightColor); rightNumberAxis.setTickLabelPaint(waveHeightColor); rightNumberAxis.setLowerBound(lowBound); rightNumberAxis.setUpperBound(upperBound); rightNumberAxis.setTickUnit(new NumberTickUnit(tick)); List<Date> shortTermTime = this.getShortTermTime(waveDirection.getTime().get(0)); //set thte plot wave height color to be transparent if show wave height is false if (!plotWaveHeight) { waveHeightColor = new Color(0, 0, 0, 0); } // plot style plotStyle = waveStyleBuilder.spline(SplineStyle.HYBRID).stroke(new BasicStroke(2.0f)) .seriesColor(waveHeightColor).numberAxis(leftNumberAxis).nonNegative(true).build(); //Draw the wave height even if plotWaveHeight is false (but with transparent in such a case) //for the purpose to keep the same background grid and tick label on the y-axis //no matter the wave height is shown or not plotter.addLineChart(TimeBase.SECOND, waveHeight, plotStyle); plotter.getPlot().setRangeAxis(1, rightNumberAxis); plotter.getPlot().setOutlineVisible(true); // 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() - 1); plotter.setDomainRange(minDate, maxDate); plotter.setDomainDateFormat(timezone, "HH"); // 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); if (plotWaveDirection) { List<Date> symbolTimes = Utility.filterMinimumHourInterval(waveDirection.getTime(), 2, 1); InListFromDateFilter symbolTimesFilter = new InListFromDateFilter(symbolTimes); waveDirection.filter(symbolTimesFilter); waveHeight = null; if (plotWaveHeight) { waveHeight = getOceanForecastDataModel().getPhenomenen(PhenomenonName.WaveHeight.toString(), NumberPhenomenon.class); waveHeight.filter(symbolTimesFilter); } plotStyle = waveStyleBuilder.seriesColor(waveDirectionColor).build(); plotter.addArrowDirectionPlot(waveDirection, waveHeight, 0.1, plotStyle); } plotter.getPlot().setRangeZeroBaselineVisible(false); return plotter.getPlot(); }
From source file:de.unijena.bioinf.FragmentationTreeConstruction.computation.recalibration.MedianSlope.java
public double[][] getMedianSubsetFairDistributed(final Spectrum<Peak> measured, final Spectrum<Peak> reference) { // for each mass range of 100 Da choose the most intensive peaks final SimpleSpectrum massOrderedSpectrum = new SimpleSpectrum(measured); final double highestMass = massOrderedSpectrum.getMzAt(massOrderedSpectrum.size() - 1); final ArrayList<Integer>[] chosenPeaks = new ArrayList[(int) Math.ceil(highestMass / 100)]; for (int k = 0; k < chosenPeaks.length; ++k) chosenPeaks[k] = new ArrayList<Integer>(); for (int k = 0; k < massOrderedSpectrum.size(); ++k) { final int bin = (int) Math.floor(massOrderedSpectrum.getMzAt(k) / 100); chosenPeaks[bin].add(k);// w ww. j a va 2 s . co m } for (int k = 0; k < chosenPeaks.length; ++k) { Collections.sort(chosenPeaks[k], new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return new Double(measured.getIntensityAt(o2)).compareTo(measured.getIntensityAt(o1)); } }); } while (chosenPeaks[chosenPeaks.length - 1].size() < 4) { chosenPeaks[chosenPeaks.length - 1].add(massOrderedSpectrum.size() - 1); } // take median of bin size Arrays.sort(chosenPeaks, new Comparator<ArrayList<Integer>>() { @Override public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { return o2.size() - o1.size(); } }); final int median = Math.max(5, chosenPeaks[chosenPeaks.length / 2].size()); //System.err.println(median); final TIntArrayList allPeaks = new TIntArrayList(); for (ArrayList<Integer> bin : chosenPeaks) allPeaks.addAll(bin.subList(0, Math.min(bin.size(), median))); // assuming that all peaks are correct, choose all peaks for recalibration final double[][] peaks = new double[2][allPeaks.size()]; for (int k = 0; k < allPeaks.size(); ++k) { peaks[0][k] = measured.getMzAt(allPeaks.get(k)); peaks[1][k] = reference.getMzAt(allPeaks.get(k)); } return peaks; }
From source file:bb.mcmc.analysis.GewekeConvergeStat.java
@Override protected double calculateEachStat(String key) { final double[] t = traceValues.get(key); final int length = t.length; final int indexStart = (int) Math.floor(length * (1 - frac2)); final int indexEnd = (int) Math.ceil(length * frac1); final double[] dStart = Arrays.copyOfRange(t, 0, indexEnd); final double[] dEnd = Arrays.copyOfRange(t, indexStart, length); final double meanStart = DiscreteStatistics.mean(dStart); final double meanEnd = DiscreteStatistics.mean(dEnd); final double varStart = ConvergeStatUtils.spectrum0(dStart) / dStart.length; final double varEnd = ConvergeStatUtils.spectrum0(dEnd) / dEnd.length; final double bothVar = varStart + varEnd; double stat = (meanStart - meanEnd) / Math.sqrt(bothVar); if (Double.isNaN(stat)) { //Use two separate if to handle other NaN cases later if (Double.isNaN(bothVar)) { stat = Double.NEGATIVE_INFINITY; System.err.println(STATISTIC_NAME + " could not be calculated for variable with id " + key + ". This is due to logged values being unchanged during the run");//. Check log file for details. "); }//from w w w .ja v a2 s .c o m } return stat; }
From source file:org.onebusaway.nyc.vehicle_tracking.impl.inference.BlockStateService.java
public BlockState getBestBlockLocation(Observation observation, BlockInstance blockInstance, double blockDistanceFrom, double blockDistanceTo) { blockDistanceFrom = Math.floor(blockDistanceFrom / _threshold) * _threshold; blockDistanceTo = Math.ceil(blockDistanceTo / _threshold) * _threshold; BlockLocationKey key = new BlockLocationKey(blockInstance, blockDistanceFrom, blockDistanceTo); Map<BlockLocationKey, BlockState> m = _observationCache.getValueForObservation(observation, EObservationCacheKey.BLOCK_LOCATION); if (m == null) { m = new HashMap<BlockStateService.BlockLocationKey, BlockState>(); _observationCache.putValueForObservation(observation, EObservationCacheKey.BLOCK_LOCATION, m); }/*w ww . ja va 2 s . c om*/ BlockState blockState = m.get(key); _cacheAccessCount++; if (blockState == null) { _cacheMissCount++; blockState = getUncachedBestBlockLocation(observation, blockInstance, blockDistanceFrom, blockDistanceTo); m.put(key, blockState); } //_log.info("cache: " + _cacheMissCount + " / " + _cacheAccessCount); return blockState; }
From source file:br.upe.ecomp.doss.algorithm.pso.PSO.java
public void reInitParticles(double percent, PSOParticle[] particles) { if (getProblem().getChangeStep() != 0) { if (getIterations() > 0 && getIterations() % getProblem().getChangeStep() == 0) { int newPerticlesNum = (int) Math.floor(getSwarmSize() * (percent / 100)); for (int i = 0; i < newPerticlesNum; i++) { particles[i] = newParticle(); }// ww w. j a va2s. c o m } } }