List of usage examples for java.lang Math floor
public static double floor(double a)
From source file:adapters.XYChartAdapter.java
private double[] adjustRangeBounds(double bmin, double bmax) { // resets chart lower and upper bounds to round values. // Returns corrected [lowerBound, upperBound] double del = (bmax - bmin) / 20.0; // Choose 20 intervals to round int a = (int) Math.floor(0.5 + Math.log10(del)); double d = Math.pow(10.0, (double) a); // power of 10 double lower = d * Math.ceil((bmin - del) / d); if (lower > bmin) lower -= d;//from w w w . j a v a 2 s . c o m if (0 == Math.abs(bmin)) lower = 0; double upper = d * Math.floor((bmax + del) / d); if (upper < bmax) upper += d; double[] range = new double[2]; range[0] = lower; range[1] = upper; return range; }
From source file:main.java.utils.Utility.java
public static int intHash(int key) { // int w = 4; // Number of bits // int p = Global.partitions; // number of slots i.e., 16 partitions // int m = 2^p; // // int s = 13; // Must have 0 < s < 2^w. Let, s = 9973 (Prime number) // int A = s/2^w; // Or, 0.5*(sqrt(5) - 1) //// //w w w .j ava 2 s.com //// // h(k) = m (kA mod 1) // return (int) Math.floor(m*((key*A)%1)); //-------------------------------------------- // int s = (int) Math.floor((double)(key * 2^w)); // int x = k*s; // return (x >> (w-p)); //-------------------------------------------- // int p = 20; // m = 2^20 // int w = 32; // int A = (int) 2654435769L; // // return (key * A) >>> (w - p); //-------------------------------------------- double A = 0.6180339887; int m = 65536; //2^(Global.partitions); return (int) Math.floor(m * ((key * A) % 1)); }
From source file:dk.dma.msinm.web.OsmStaticMap.java
public void initCoords(MapImageCtx ctx) { ctx.centerX = lonToTile(ctx.lon, ctx.zoom); ctx.centerY = latToTile(ctx.lat, ctx.zoom); ctx.offsetX = Math.floor((Math.floor(ctx.centerX) - ctx.centerX) * ctx.tileSize); ctx.offsetY = Math.floor((Math.floor(ctx.centerY) - ctx.centerY) * ctx.tileSize); }
From source file:edu.umn.cs.spatialHadoop.nasa.SpatioTemporalAggregateQuery.java
/** * Performs a spatio-temporal aggregate query on an indexed directory * @param inFile// w w w . j av a 2 s .c o m * @param params * @throws ParseException * @throws IOException */ public static AggregateQuadTree.Node aggregateQuery(Path inFile, OperationsParams params) throws ParseException, IOException { // 1- Run a temporal filter step to find all matching temporal partitions Vector<Path> matchingPartitions = new Vector<Path>(); // List of time ranges to check. Initially it contains one range as // specified by the user. Eventually, it can be split into at most two // partitions if partially matched by a partition. Vector<TimeRange> temporalRanges = new Vector<TimeRange>(); temporalRanges.add(new TimeRange(params.get("time"))); Path[] temporalIndexes = new Path[] { new Path(inFile, "yearly"), new Path(inFile, "monthly"), new Path(inFile, "daily") }; int index = 0; final FileSystem fs = inFile.getFileSystem(params); while (index < temporalIndexes.length && !temporalRanges.isEmpty()) { Path indexDir = temporalIndexes[index]; LOG.info("Checking index dir " + indexDir); TemporalIndex temporalIndex = new TemporalIndex(fs, indexDir); for (int iRange = 0; iRange < temporalRanges.size(); iRange++) { TimeRange range = temporalRanges.get(iRange); TemporalPartition[] matches = temporalIndex.selectContained(range.start, range.end); if (matches != null) { LOG.info("Matched " + matches.length + " partitions in " + indexDir); for (TemporalPartition match : matches) { LOG.info("Matched temporal partition: " + match.dirName); matchingPartitions.add(new Path(indexDir, match.dirName)); } // Update range to remove matching part TemporalPartition firstMatch = matches[0]; TemporalPartition lastMatch = matches[matches.length - 1]; if (range.start < firstMatch.start && range.end > lastMatch.end) { // Need to split the range into two temporalRanges.setElementAt(new TimeRange(range.start, firstMatch.start), iRange); temporalRanges.insertElementAt(new TimeRange(lastMatch.end, range.end), iRange); } else if (range.start < firstMatch.start) { // Update range in-place range.end = firstMatch.start; } else if (range.end > lastMatch.end) { // Update range in-place range.start = lastMatch.end; } else { // Current range was completely covered. Remove it temporalRanges.remove(iRange); } } } index++; } numOfTemporalPartitionsInLastQuery = matchingPartitions.size(); // 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()); } } // 3- Query all matching files in parallel Vector<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++) { try { Path matchingFile = allMatchingFiles.get(i_file); 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) * 1200); int y1 = (int) (Math.max(translated.y1, 0) * 1200); int x2 = (int) (Math.min(translated.x2, 1.0) * 1200); int y2 = (int) (Math.min(translated.y2, 1.0) * 1200); AggregateQuadTree.Node fileResult = AggregateQuadTree.aggregateQuery(fs, matchingFile, new java.awt.Rectangle(x1, y1, (x2 - x1), (y2 - y1))); threadResult.accumulate(fileResult); } catch (IOException e) { e.printStackTrace(); } } return threadResult; } }); AggregateQuadTree.Node finalResult = new AggregateQuadTree.Node(); for (Node threadResult : threadsResults) finalResult.accumulate(threadResult); numOfTreesTouchesInLastRequest = allMatchingFiles.size(); return finalResult; }
From source file:emlab.domain.factory.ElectricityProducerFactory.java
private int getRandomIndexFromList(int size) { return (int) Math.min(Math.floor(Math.random() * size), size - 1); }
From source file:ffx.numerics.fft.RowMajorComplex3DCuda.java
/** * {@inheritDoc}//ww w.j a v a2 s . c o m */ @Override public void run() { JCudaDriver.setExceptionsEnabled(true); JCufft.setExceptionsEnabled(true); JCudaDriver.setLogLevel(LogLevel.LOG_ERROR); // Initialize the driver and create a context for the first device. cuInit(0); CUcontext pctx = new CUcontext(); CUdevice dev = new CUdevice(); CUdevprop prop = new CUdevprop(); cuDeviceGetProperties(prop, dev); logger.info(" CUDA " + prop.toFormattedString()); cuDeviceGet(dev, 0); cuCtxCreate(pctx, 0, dev); KernelLauncher kernelLauncher = null; // Load the CUBIN file and obtain the "recipSummation" function. try { String bit = System.getProperty("sun.arch.data.model").trim(); URL source = getClass().getClassLoader() .getResource("ffx/numerics/fft/recipSummation-" + bit + ".cubin"); File cubinFile = File.createTempFile("recipSummation", "cubin"); FileUtils.copyURLToFile(source, cubinFile); String kernelPath = cubinFile.getCanonicalPath(); kernelLauncher = KernelLauncher.load(kernelPath, "recipSummation"); } catch (Exception e) { String message = "Error loading the reciprocal summation kernel"; logger.log(Level.SEVERE, message, e); } // Copy the data array to the device. dataDevice = new CUdeviceptr(); cuMemAlloc(dataDevice, len * 2 * Sizeof.DOUBLE); dataPtr = Pointer.to(data); cuMemcpyHtoD(dataDevice, dataPtr, len * 2 * Sizeof.DOUBLE); // Copy the recip array to the device. recipDevice = new CUdeviceptr(); cuMemAlloc(recipDevice, len * Sizeof.DOUBLE); recipPtr = Pointer.to(recip); cuMemcpyHtoD(recipDevice, recipPtr, len * Sizeof.DOUBLE); // Create a CUFFT plan for the data plan = new cufftHandle(); cufftPlan3d(plan, nX, nY, nZ, cufftType.CUFFT_Z2Z); int threads = 512; int nBlocks = len / threads + (len % threads == 0 ? 0 : 1); int gridSize = (int) Math.floor(Math.sqrt(nBlocks)) + 1; dim3 gridDim = new dim3(gridSize, gridSize, 1); dim3 blockDim = new dim3(threads, 1, 1); kernelLauncher.setup(gridDim, blockDim); logger.info(format(" CUDA thread initialized with %d threads per block", threads)); logger.info(format(" Grid Size: (%d x %d x 1).", gridSize, gridSize)); assert (gridSize * gridSize * threads >= len); synchronized (this) { while (!free) { if (doConvolution) { cuMemcpyHtoD(dataDevice, dataPtr, len * 2 * Sizeof.DOUBLE); cufftExecC2C(plan, dataDevice, dataDevice, CUFFT_FORWARD); kernelLauncher.call(dataDevice, recipDevice, len); cufftExecC2C(plan, dataDevice, dataDevice, CUFFT_INVERSE); cuMemcpyDtoH(dataPtr, dataDevice, len * 2 * Sizeof.DOUBLE); doConvolution = false; notify(); } try { wait(); } catch (InterruptedException e) { logger.severe(e.toString()); } } cufftDestroy(plan); cuMemFree(dataDevice); cuMemFree(recipDevice); dead = true; notify(); } logger.info(" CUDA Thread Done!"); }
From source file:io.github.sunggu.searchimage.ui.ImageGridFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.image_search_fragment, container, false); edtSearchKeyword = (EditText) v.findViewById(R.id.search_keyword); edtSearchKeyword.addTextChangedListener(new TextWatcher() { @Override/* w w w . j a v a2 s . c o m*/ public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { OpenApi.getInstance().requestSearchImage(s.toString(), mResponseListener, mErrorListener); } }); final GridView mGridView = (GridView) v.findViewById(R.id.search_result_grid); mGridView.setAdapter(mAdapter); mGridView.setOnItemClickListener(this); mGridView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int scrollState) { // Pause fetcher to ensure smoother scrolling when flinging if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) { // Before Honeycomb pause image loading on scroll to help with performance if (!Utils.hasHoneycomb()) { mImageFetcher.setPauseWork(true); } } else { mImageFetcher.setPauseWork(false); } } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); // This listener is used to get the final width of the GridView and then calculate the // number of columns and the width of each column. The width of each column is variable // as the GridView has stretchMode=columnWidth. The column width is used to set the height // of each view so we get nice square thumbnails. mGridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @TargetApi(VERSION_CODES.JELLY_BEAN) @Override public void onGlobalLayout() { if (mAdapter.getNumColumns() == 0) { final int numColumns = (int) Math .floor(mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing)); if (numColumns > 0) { final int columnWidth = (mGridView.getWidth() / numColumns) - mImageThumbSpacing; mAdapter.setNumColumns(numColumns); mAdapter.setItemHeight(columnWidth); if (BuildConfig.DEBUG) { Log.d(TAG, "onCreateView - numColumns set to " + numColumns); } if (Utils.hasJellyBean()) { mGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { mGridView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } } } } }); return v; }
From source file:no.met.jtimeseries.marinogram.MarinogramTemperaturePlot.java
private XYPlot createPlot(TimeZone timezone, boolean plotAirTemp, boolean plotWaterTemp, boolean plotDewpointTemp) throws ParseException { Date startTime = null;//from w ww . j ava 2s . c o m NumberPhenomenon aTemperature = null; NumberPhenomenon wTemperature = null; NumberPhenomenon dTemperature = null; // default setting ChartPlotter plotter = new ChartPlotter(); plotter.setHeight(this.getHeight()); plotter.setWidth(this.getWidth()); plotter.setPlotDefaultProperties("", ""); double minValue = 100; double maxValue = -100; int plotIndex = 0; if (plotAirTemp) { aTemperature = getLocationForecastDataModel().getPhenomenen(PhenomenonName.AirTemperature.toString(), NumberPhenomenon.class); minValue = aTemperature.getMinValue() < minValue ? aTemperature.getMinValue() : minValue; maxValue = aTemperature.getMaxValue() > maxValue ? aTemperature.getMaxValue() : maxValue; startTime = aTemperature.getTime().get(0); plotTemperature(plotter, aTemperature, new BasicStroke(2.0f), Color.RED, messages.getString("label.air"), true); plotter.getPlot().getRenderer(plotIndex).setSeriesVisibleInLegend(0, true); plotter.getPlot().getRenderer(plotIndex).setSeriesVisibleInLegend(1, true); plotIndex++; } if (plotWaterTemp) { wTemperature = getOceanForecastDataModel().getPhenomenen(PhenomenonName.seaTemperature.toString(), NumberPhenomenon.class); // only plot water temperature if it is availbe for this location if (wTemperature != null) { minValue = wTemperature.getMinValue() < minValue ? wTemperature.getMinValue() : minValue; maxValue = wTemperature.getMaxValue() > maxValue ? wTemperature.getMaxValue() : maxValue; startTime = wTemperature.getTime().get(0); BasicStroke dottedStroke = new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] { 2.0f, 6.0f }, 0.0f); plotTemperature(plotter, wTemperature, dottedStroke, Color.RED, messages.getString("label.water"), true); plotter.getPlot().getRenderer(plotIndex++).setSeriesVisibleInLegend(0, true); } } if (plotDewpointTemp) { dTemperature = getLocationForecastDataModel() .getPhenomenen(PhenomenonName.dewPointTemperature.toString(), NumberPhenomenon.class); minValue = dTemperature.getMinValue() < minValue ? dTemperature.getMinValue() : minValue; maxValue = dTemperature.getMaxValue() > maxValue ? dTemperature.getMaxValue() : maxValue; startTime = dTemperature.getTime().get(0); plotTemperature(plotter, dTemperature, new BasicStroke(2.0f), Color.ORANGE, messages.getString("label.dewpoint"), false); plotter.getPlot().getRenderer(plotIndex).setSeriesVisibleInLegend(0, true); } double tick = (maxValue - minValue) / 3.5; tick = Math.ceil(tick); double lowBound = Math.floor(minValue / (tick)) * (tick); lowBound = lowBound - tick / 2; double upperBound = lowBound + tick * 7; // set range axis NumberAxis numberAxis = new NumberAxis(); numberAxis.setLabelPaint(Color.RED); numberAxis.setTickLabelPaint(Color.RED); numberAxis.setLabel(messages.getString("parameter.temperature") + " (\u00B0 C)"); numberAxis.setTickUnit(new NumberTickUnit(tick)); numberAxis.setLowerBound(lowBound); numberAxis.setUpperBound(upperBound); //Set left axis and right axis plotter.getPlot().setRangeAxis(0, numberAxis); plotter.getPlot().setRangeAxis(1, numberAxis); //Set the third axis and hide the third axis if (plotAirTemp && plotWaterTemp && plotDewpointTemp) { NumberAxis numberAxis2 = new NumberAxis(); numberAxis2.setTickUnit(new NumberTickUnit(tick)); numberAxis2.setLowerBound(lowBound); numberAxis2.setUpperBound(upperBound); plotter.getPlot().setRangeAxis(2, numberAxis2); plotter.getPlot().getRangeAxis(2).setVisible(false); } //Show legend at the top right position of the plot LegendTitle lt = new LegendTitle(plotter.getPlot()); lt.setItemFont(new Font("Dialog", Font.PLAIN, 9)); lt.setBackgroundPaint(new Color(255, 255, 255, 100)); lt.setFrame(new BlockBorder(Color.white)); lt.setPosition(RectangleEdge.TOP); XYTitleAnnotation ta = new XYTitleAnnotation(0.99, 0.95, lt, RectangleAnchor.TOP_RIGHT); plotter.getPlot().addAnnotation(ta); // set domain range after (must) plot all the data plotter.addHourBasedDomainGridLines(); // add markers plotter.addDomainMarkers(getShortTermTime(startTime), timezone, locale); Date minDate = getShortTermTime(startTime).get(0); Date maxDate = getShortTermTime(startTime).get(getShortTermTime(startTime).size() - 1); plotter.setDomainRange(minDate, maxDate); plotter.setDomainDateFormat(timezone, "HH"); plotter.getPlot().setOutlineVisible(true); // invisible the domain i.e, x axis plotter.getPlot().getDomainAxis().setTickLabelsVisible(false); return plotter.getPlot(); }
From source file:com.fengduo.bee.web.controller.order.OrderController.java
/** * /*from w w w . j av a 2 s .co m*/ * * @param subType :1.2. * @param subAmount ? * @param advances ??? * @param handlingCost */ @RequestMapping(value = "/sub/add", produces = "application/json", method = RequestMethod.POST) @ResponseBody public JsonResult sub(Long itemId, Integer subType, Float subAmount, Float advances, Float handlingCost) { if (itemId == null || subType == null || subAmount == null) { return JsonResultUtils.error("????"); } if (SubUserTypeEnum.getEnum(subType) == null) { return JsonResultUtils.error("????"); } if (subType == SubUserTypeEnum.FOLLOW_SUB.getValue()) { if (advances == null) { return JsonResultUtils.error("???"); } } ShiroUser currentUser = getCurrentUser(); // ????? if (!currentUser.isIdentity()) { return JsonResultUtils.error("????"); } Item item = itemService.getItemById(itemId); if (item == null) { return JsonResultUtils.error("?!"); } // ??-- if (!VerifyStatusEnum.isNormal(item.getVerifyStatus())) { return JsonResultUtils.error("!"); } if (!ProgressEnum.isLegalSubProgress(item.getProgress(), subType)) { return JsonResultUtils.error("??"); } ItemFinance itemFinance = itemService.getItemFinanceByItemId(itemId); if (itemFinance != null) { // ??? if (itemFinance.isReachAmount()) { return JsonResultUtils.error("??"); } } float fold = subAmount / itemFinance.getPerStock(); if ((fold - Math.floor(fold)) > 0) { return JsonResultUtils.error("???"); } if (subAmount >= itemFinance.getAmount()) { return JsonResultUtils.error("???"); } if (subType == SubUserTypeEnum.CORNERSTONE_SUB.getValue()) { if (subAmount < itemFinance.getAmount() * 0.1) { return JsonResultUtils.error("????10%"); } } // ????? UserSub existSub = orderService.findUnCloseSub(currentUser.getId(), itemId); if (existSub != null) { return JsonResultUtils.error("??"); } // ? Parameter query = Parameter.newParameter()// .pu("itemId", itemId)// .pu("userType", SubUserTypeEnum.CORNERSTONE_SUB.getValue())// .pu("handleStatus", SubHandleStatusEnum.DEPOSIT_SUCCESS_PAY.getValue()); UserSub cornerstoneSub = orderService.findUserSub(query); // ?? Result subResult = createUserSub(cornerstoneSub, currentUser, subType, subAmount, advances, item, itemFinance); if (subResult.isFailed()) { return JsonResultUtils.error(subResult.getMessage()); } Result orderResult = createOrder(item, currentUser, subAmount, handlingCost, subType); UserSub userSub = (UserSub) subResult.getData(); PayOrder order = (PayOrder) orderResult.getData(); boolean flag = orderService.insertSubAndOrder(userSub, order); if (flag) { Map<String, Object> dataMap = new HashMap<String, Object>(); dataMap.put("itemId", itemId); dataMap.put("orderId", order.getId()); dataMap.put("subId", userSub.getId()); return JsonResultUtils.success(dataMap); } else { return JsonResultUtils.error(""); } }
From source file:bb.mcmc.analysis.ConvergeStatUtils.java
private static double calSpectrum0(double[] newData) { final int N = newData.length; final int Nfreq = (int) Math.floor(N / 2); final double oneOverN = 1.0 / N; double[] freq = new double[Nfreq]; double[] f1 = new double[Nfreq]; for (int i = 0; i < Nfreq; i++) { freq[i] = oneOverN * (i + 1);/*from ww w. j a v a 2 s .c o m*/ f1[i] = SQRT3 * (4 * freq[i] - 1); } double[] complexArray = ConvergeStatUtils.realToComplexArray(newData); double[] spec = new double[N]; DoubleFFT_1D fft = new DoubleFFT_1D(N); fft.complexForward(complexArray); for (int i = 0; i < N; i++) { Complex complexData = new Complex(complexArray[i * 2], complexArray[i * 2 + 1]); complexData = complexData.multiply(complexData.conjugate()); spec[i] = complexData.getReal() / N; } spec = Arrays.copyOfRange(spec, 1, f1.length + 1); double[] coefficients = gammaGLM.coefficients(spec, f1); double v = Math.exp(coefficients[0] + coefficients[1] * -SQRT3); return v; }