List of usage examples for java.lang Float isNaN
public static boolean isNaN(float v)
From source file:WeakIdentityHashMap.java
/** * Constructs a new, empty <tt>WeakIdentityHashMap</tt> with the given * initial capacity and the given load factor. * /* ww w .j ava2s . co m*/ * @param initialCapacity * The initial capacity of the <tt>WeakIdentityHashMap</tt> * @param loadFactor * The load factor of the <tt>WeakIdentityHashMap</tt> * @throws IllegalArgumentException * If the initial capacity is negative, or if the load factor is * nonpositive. */ public WeakIdentityHashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Initial Capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal Load factor: " + loadFactor); int capacity = 1; while (capacity < initialCapacity) capacity <<= 1; table = new Entry[capacity]; this.loadFactor = loadFactor; threshold = (int) (capacity * loadFactor); }
From source file:ffx.numerics.fft.Real3DCuda.java
/** * <p>//w w w.j av a 2s. c o m * main</p> * * @param args an array of {@link java.lang.String} objects. * @throws java.lang.Exception if any. */ public static void main(String[] args) throws Exception { int dimNotFinal = 64; int reps = 10; if (args != null) { try { dimNotFinal = Integer.parseInt(args[0]); if (dimNotFinal < 1) { dimNotFinal = 64; } reps = Integer.parseInt(args[1]); if (reps < 1) { reps = 5; } } catch (Exception e) { } } if (dimNotFinal % 2 != 0) { dimNotFinal++; } final int dim = dimNotFinal; System.out.println(String.format( "Initializing a %d cubed grid.\n" + "The best timing out of %d repititions will be used.", dim, reps)); final int dimCubed = dim * dim * dim; final int dimCubed2 = (dim + 2) * dim * dim; /** * Create an array to save the initial input and result. */ final double orig[] = new double[dimCubed2]; final double answer[] = new double[dimCubed2]; final double data[] = new double[dimCubed2]; final double recip[] = new double[dimCubed]; final float origf[] = new float[dimCubed2]; final float dataf[] = new float[dimCubed2]; final float recipf[] = new float[dimCubed]; Random randomNumberGenerator = new Random(1); int index = 0; int index2 = 0; /** * Row-major order. */ for (int x = 0; x < dim; x++) { for (int y = 0; y < dim; y++) { for (int z = 0; z < dim; z++) { float randomNumber = randomNumberGenerator.nextFloat(); orig[index] = randomNumber; origf[index] = randomNumber; index++; recip[index2] = 1.0; recipf[index2] = 1.0f; index2++; } // Padding index += 2; } } Real3D real3D = new Real3D(dim, dim, dim); Real3DParallel real3DParallel = new Real3DParallel(dim, dim, dim, new ParallelTeam(), IntegerSchedule.fixed()); Real3DCuda real3DCUDA = new Real3DCuda(dim, dim, dim, dataf, recipf); Thread cudaThread = new Thread(real3DCUDA); cudaThread.setPriority(Thread.MAX_PRIORITY); cudaThread.start(); double toSeconds = 0.000000001; long parTime = Long.MAX_VALUE; long seqTime = Long.MAX_VALUE; long clTime = Long.MAX_VALUE; real3D.setRecip(recip); for (int i = 0; i < reps; i++) { System.arraycopy(orig, 0, data, 0, dimCubed2); long time = System.nanoTime(); real3D.convolution(data); time = (System.nanoTime() - time); System.out.println(String.format("%2d Sequential: %8.3f", i + 1, toSeconds * time)); if (time < seqTime) { seqTime = time; } } System.arraycopy(data, 0, answer, 0, dimCubed2); real3DParallel.setRecip(recip); for (int i = 0; i < reps; i++) { System.arraycopy(orig, 0, data, 0, dimCubed2); long time = System.nanoTime(); real3DParallel.convolution(data); time = (System.nanoTime() - time); System.out.println(String.format("%2d Parallel: %8.3f", i + 1, toSeconds * time)); if (time < parTime) { parTime = time; } } double maxError = Double.MIN_VALUE; double rmse = 0.0; index = 0; for (int x = 0; x < dim; x++) { for (int y = 0; y < dim; y++) { for (int z = 0; z < dim; z++) { double error = Math.abs((orig[index] - data[index] / dimCubed)); if (error > maxError) { maxError = error; } rmse += error * error; index++; } index += 2; } } rmse /= dimCubed; rmse = Math.sqrt(rmse); logger.info(String.format("Parallel RMSE: %12.10f, Max: %12.10f", rmse, maxError)); for (int i = 0; i < reps; i++) { System.arraycopy(origf, 0, dataf, 0, dimCubed2); long time = System.nanoTime(); real3DCUDA.convolution(dataf); time = (System.nanoTime() - time); System.out.println(String.format("%2d CUDA: %8.3f", i + 1, toSeconds * time)); if (time < clTime) { clTime = time; } } real3DCUDA.free(); real3DCUDA = null; maxError = Double.MIN_VALUE; double avg = 0.0; rmse = 0.0; index = 0; for (int x = 0; x < dim; x++) { for (int y = 0; y < dim; y++) { for (int z = 0; z < dim; z++) { if (Float.isNaN(dataf[index])) { logger.info(String.format("Not a number %d %d %d", x, y, z)); System.exit(-1); } double error = Math.abs(origf[index] - dataf[index]); avg += error; if (error > maxError) { maxError = error; } rmse += error * error; index++; } index += 2; } } rmse /= dimCubed; avg /= dimCubed; rmse = Math.sqrt(rmse); logger.info(String.format("CUDA RMSE: %12.10f, Max: %12.10f, Avg: %12.10f", rmse, maxError, avg)); System.out.println(String.format("Best Sequential Time: %8.3f", toSeconds * seqTime)); System.out.println(String.format("Best Parallel Time: %8.3f", toSeconds * parTime)); System.out.println(String.format("Best CUDA Time: %8.3f", toSeconds * clTime)); System.out.println(String.format("Parallel Speedup: %15.5f", (double) seqTime / parTime)); System.out.println(String.format("CUDA Speedup: %15.5f", (double) seqTime / clTime)); }
From source file:org.dishevelled.multimap.impl.AbstractHashedMap.java
/** * Constructs a new, empty map with the specified initial capacity and * load factor.//from w w w . ja v a 2 s . com * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is less than one * @throws IllegalArgumentException if the load factor is less than or equal to zero */ protected AbstractHashedMap(int initialCapacity, float loadFactor) { super(); if (initialCapacity < 1) { throw new IllegalArgumentException("Initial capacity must be greater than 0"); } if (loadFactor <= 0.0f || Float.isNaN(loadFactor)) { throw new IllegalArgumentException("Load factor must be greater than 0"); } this.loadFactor = loadFactor; this.threshold = calculateThreshold(initialCapacity, loadFactor); int newInitialCapacity = calculateNewCapacity(initialCapacity); this.data = new HashEntry[newInitialCapacity]; init(); }
From source file:com.cloudera.oryx.common.collection.LongFloatMap.java
/** * Adds to the value for a given key. If no mapping exists for the key then the value is set as a new * value for the key.// ww w . j av a2 s .c o m * * @param key key whose value should be incremented * @param delta amount to increment value by */ public void increment(long key, float delta) { Preconditions.checkArgument(key != KEY_NULL && key != REMOVED); int index = find(key); float currentValue = values[index]; if (Float.isNaN(currentValue)) { put(key, delta); } else { values[index] = currentValue + delta; } }
From source file:org.apache.hadoop.util.Progress.java
/** Called during execution on a leaf node to set its progress. */ public synchronized void set(float progress) { if (Float.isNaN(progress)) { progress = 0;/*from w w w . ja v a 2 s.c om*/ LOG.debug("Illegal progress value found, progress is Float.NaN. " + "Progress will be changed to 0"); } else if (progress == Float.NEGATIVE_INFINITY) { progress = 0; LOG.debug("Illegal progress value found, progress is " + "Float.NEGATIVE_INFINITY. Progress will be changed to 0"); } else if (progress < 0) { progress = 0; LOG.debug("Illegal progress value found, progress is less than 0." + " Progress will be changed to 0"); } else if (progress > 1) { progress = 1; LOG.debug( "Illegal progress value found, progress is larger than 1." + " Progress will be changed to 1"); } else if (progress == Float.POSITIVE_INFINITY) { progress = 1; LOG.debug("Illegal progress value found, progress is " + "Float.POSITIVE_INFINITY. Progress will be changed to 1"); } this.progress = progress; }
From source file:model.scenario.CompetitiveScenarioTest.java
@Test public void rightPriceAndQuantityLearningFlows() { for (int competitors = 4; competitors <= 7; competitors++) { System.out.println("FORCED COMPETITIVE FIRMS: " + (competitors + 1)); for (int i = 0; i < 5; i++) { final MacroII macroII = new MacroII(System.currentTimeMillis()); final TripolistScenario scenario1 = new TripolistScenario(macroII); scenario1.setSalesDepartmentType(SalesDepartmentOneAtATime.class); scenario1.setAskPricingStrategy(InventoryBufferSalesControl.class); scenario1.setControlType(/*from w w w. j a v a2s . c o m*/ MonopolistScenario.MonopolistScenarioIntegratedControlEnum.MARGINAL_PLANT_CONTROL); scenario1.setAdditionalCompetitors(competitors); scenario1.setWorkersToBeRehiredEveryDay(true); scenario1.setDemandIntercept(102); //assign scenario macroII.setScenario(scenario1); macroII.start(); macroII.schedule.step(macroII); try { final HumanResources hr = scenario1.getMonopolist().getHRs().iterator().next(); final ErrorCorrectingPurchasePredictor predictor = new ErrorCorrectingPurchasePredictor(macroII, hr); hr.setPredictor(predictor); predictor.setDebugWriter(Paths.get("runs", "tmp.csv")); } catch (IOException e) { e.printStackTrace(); } while (macroII.schedule.getTime() < 8000) { macroII.schedule.step(macroII); /* System.out.println("sales: " + scenario1.getCompetitors().get(0).getSalesDepartment(GoodType.GENERIC). getLatestObservation(SalesDataType.OUTFLOW) +"," + scenario1.getCompetitors().get(1).getSalesDepartment(GoodType.GENERIC). getLatestObservation(SalesDataType.OUTFLOW)); */ } SummaryStatistics prices = new SummaryStatistics(); SummaryStatistics quantities = new SummaryStatistics(); SummaryStatistics target = new SummaryStatistics(); for (int j = 0; j < 500; j++) { macroII.schedule.step(macroII); assert !Float.isNaN(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayAveragePrice()); prices.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayAveragePrice()); quantities.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayVolume()); for (EconomicAgent agent : macroII.getMarket(UndifferentiatedGoodType.GENERIC).getSellers()) { SalesDepartment department = ((Firm) agent) .getSalesDepartment(UndifferentiatedGoodType.GENERIC); target.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayVolume()); } } System.out.println(prices.getMean() + " - " + quantities.getMean() + "/" + target.getMean() + "----" + macroII.seed() + " | " + macroII.getMarket(UndifferentiatedGoodType.GENERIC).getLastDaysAveragePrice()); System.out.println("standard deviations: price : " + prices.getStandardDeviation() + " , quantity: " + quantities.getStandardDeviation()); OneSectorStatics.printSlopes(scenario1); if (competitors >= 4) { assertEquals(prices.getMean(), 58, 5); assertTrue(prices.getStandardDeviation() < 5.5); assertEquals(quantities.getMean(), 44, 5); assertTrue(quantities.getStandardDeviation() < 5.5); } macroII.finish(); } } }
From source file:savant.diff.DiffDataSource.java
/** * Because the two input data-sources may be returning differing numbers of records, * we may have to interpolate. Arbitrarily, we decide that inputA provides the * bench-mark and inputB gets interpolated. *///from w ww . ja v a 2 s . c o m private float interpolate(List<? extends ContinuousRecord> bRecords, int j, int pos) { float result = 0.0f; if (j < bRecords.size()) { ContinuousRecord recB = bRecords.get(j); if (recB.getPosition() == pos || j == 0) { // Simple case. We have a data-point at the exact position. result = recB.getValue(); } else if (recB.getPosition() > pos) { // If we got here, recB is further on in the chromosome than pos, so we need to interpolate with the preceding data-point. ContinuousRecord prevRecB = bRecords.get(j - 1); float weight = (float) (pos - prevRecB.getPosition()) / (recB.getPosition() - prevRecB.getPosition()); result = prevRecB.getValue() * weight + recB.getValue() * (1.0f - weight); } } return Float.isNaN(result) ? 0.0f : result; }
From source file:org.deegree.tools.rendering.dem.builder.DEMDatasetGenerator.java
/** * Creates a new <code>PatchGenerator</code> instance. * /*from w ww . j av a 2s .c o m*/ * @param raster * the dem raster * @param options * containing information on the given raster. * @param levels * number of levels in the generated (layered) DAG * @param rowsPerTile * number of rows per macro triangle (tile) * @param maxZ * the clipping z value. * @throws SQLException * @throws IOException */ public DEMDatasetGenerator(AbstractRaster raster, RasterIOOptions options, int levels, int rowsPerTile, float maxZ) throws SQLException, IOException { this.dataBuffer = buildGrid(raster, options); if (Float.isNaN(maxZ)) { this.maxZ = getAsFloatSample(-1, -1, 0); System.out.println("Setting max height value to no data value: " + this.maxZ); } else { this.maxZ = maxZ; } // don't use dataBuffer.getWidth() here, as it seems to be happen that // it gets bigger than the input // raster (e.g. 2048 -> 2049) this.inputX = raster.getColumns(); this.inputY = raster.getRows(); this.rowsPerFragment = rowsPerTile; RasterGeoReference rRef = raster.getRasterReference(); sampleSizeX = rRef.getResolutionX(); sampleSizeY = rRef.getResolutionY(); this.geoReference = new RasterGeoReference(OriginLocation.CENTER, rRef.getResolutionX(), rRef.getResolutionY(), rRef.getRotationX(), rRef.getRotationY(), 0, raster.getEnvelope().getSpan1(), raster.getCoordinateSystem()); // calculate the best size int numSamples = Math.max(inputX, inputY); int nextPowerOfTwo = MathUtils.nextPowerOfTwoValue(numSamples); this.outputX = nextPowerOfTwo; this.outputY = nextPowerOfTwo; Envelope env = raster.getRasterReference().getEnvelope(new RasterRect(0, 0, outputX, outputY), null); Point2f p0 = new Point2f(0, (float) env.getSpan1()); Point2f p1 = new Point2f(0, 0); Point2f p2 = new Point2f((float) env.getSpan0(), (float) env.getSpan1()); int lowestLevel = Integer.numberOfTrailingZeros(rowsPerTile); int heighestLevel = Integer.numberOfTrailingZeros(outputX); int tL = (heighestLevel - lowestLevel) * 2; if (levels == -1) { System.out .println("Setting number of levels for " + rowsPerTile + " rows per macro triangle to: " + tL); this.levels = tL; } else { this.levels = levels; } if (tL != this.levels) { System.out.println("++++WARN++++\nThe best number of levels (fitting your data) for " + rowsPerTile + " rows per macro triangle is " + tL + ". You provided: " + levels + ", this will result in " + ((levels < tL) ? "under" : "over") + " sampling your input data.\n++++++++++++"); } /** * rb: a macro triangle will consist of all inner vertices + the 'half-way' vertices which make sure that two * triangles will fit together. for example: <code> * rowsPerTile = 2; * verticersPerTile = 4 * 4 - 3 = 13 * (dots are vertices) * . * :/.\: * :/...\: * </code> * */ this.verticesPerFragment = (rowsPerTile + 2) * (rowsPerTile + 2) - 3; // rb: draw it out, it is working. this.trianglesPerFragment = (4 * rowsPerTile) + (2 * (rowsPerTile - 1) * rowsPerTile); if (getVerticesPerFragment() > 65536) { throw new RuntimeException(Messages.getMessage("DEMDSGEN_TOO_MANY_VERTICES")); } int bytesPerMacroTriangle = (4 + 4 * 3 * getVerticesPerFragment()); // normal vectors this.bytesPerTile = (bytesPerMacroTriangle + (BYTES_PER_NORMAL_COMPONENT * 3 * getVerticesPerFragment())); long fs = 0; int level = 0; while (level < this.levels) { fs += bytesPerTile * (2l << level++); } fileSize = fs; double minX = raster.getEnvelope().getMin().get0(); double minY = raster.getEnvelope().getMin().get1(); double maxX = raster.getEnvelope().getMax().get0(); double maxY = raster.getEnvelope().getMax().get1(); System.out.println("\nInitializing DEMDatasetGenerator"); System.out.println("--------------------------------\n"); // System.out.println( "- input file: " + inputFileName ); System.out.println("- envelope: (" + minX + "," + minY + ")-(" + maxX + "," + maxY + ")"); System.out.println("- raster sample size: x=" + sampleSizeX + ", y=" + sampleSizeY); System.out.println("- bintritree levels: " + levels); System.out.println("- rows per tile: " + rowsPerTile); System.out.println("- vertices per tile: " + getVerticesPerFragment()); System.out.println("- triangles per tile: " + getTrianglesPerFragment()); System.out.println("- bytes per tile: " + getBytesPerTile()); System.out.println("- filesize will be: " + fileSize + " bytes (" + Math.round((fileSize / (1024 * 1024d)) * 100d) / 100d + " Mb)"); System.out.println("- WPVS translationvector should be: <TranslationToLocalCRS x=\"-" + minX + "\" y=\"-" + minY + "\"/>"); outputTriangleHeights(p0, p1, p2, this.getLevels()); }
From source file:org.janusgraph.core.attribute.Geoshape.java
/** * Returns the {@link Type} of this geoshape. * * @return/*from w w w. j a va 2 s . c o m*/ */ public Type getType() { if (coordinates[0].length == 1) return Type.POINT; else if (coordinates[0].length > 2) return Type.POLYGON; else { //coordinates[0].length==2 if (Float.isNaN(coordinates[0][1])) return Type.CIRCLE; else return Type.BOX; } }
From source file:IEEE754rUtils.java
/** * <p>Gets the maximum of two <code>float</code> values.</p> * /*from w w w .java 2 s . c o m*/ * <p>NaN is only returned if all numbers are NaN as per IEEE-754r. </p> * * @param a value 1 * @param b value 2 * @return the largest of the values */ public static float max(float a, float b) { if (Float.isNaN(a)) { return b; } else if (Float.isNaN(b)) { return a; } else { return Math.max(a, b); } }