List of usage examples for java.util Random nextFloat
public float nextFloat()
From source file:org.apache.hadoop.hive.serde2.binarysortable.MyTestPrimitiveClass.java
public int randomFill(Random r, int randField, int field, ExtraTypeInfo extraTypeInfo) { myBool = chooseNull(r, randField, field++) ? null : Boolean.valueOf(r.nextInt(1) == 1); myByte = chooseNull(r, randField, field++) ? null : Byte.valueOf((byte) r.nextInt()); myShort = chooseNull(r, randField, field++) ? null : Short.valueOf((short) r.nextInt()); myInt = chooseNull(r, randField, field++) ? null : Integer.valueOf(r.nextInt()); myLong = chooseNull(r, randField, field++) ? null : Long.valueOf(r.nextLong()); myFloat = chooseNull(r, randField, field++) ? null : Float.valueOf(r.nextFloat() * 10 - 5); myDouble = chooseNull(r, randField, field++) ? null : Double.valueOf(r.nextDouble() * 10 - 5); myString = chooseNull(r, randField, field++) ? null : getRandString(r); myHiveChar = chooseNull(r, randField, field++) ? null : getRandHiveChar(r, extraTypeInfo); myHiveVarchar = chooseNull(r, randField, field++) ? null : getRandHiveVarchar(r, extraTypeInfo); myBinary = getRandBinary(r, r.nextInt(1000)); myDecimal = chooseNull(r, randField, field++) ? null : getRandHiveDecimal(r, extraTypeInfo); myDate = chooseNull(r, randField, field++) ? null : getRandDate(r); myTimestamp = chooseNull(r, randField, field++) ? null : RandomTypeUtil.getRandTimestamp(r); myIntervalYearMonth = chooseNull(r, randField, field++) ? null : getRandIntervalYearMonth(r); myIntervalDayTime = chooseNull(r, randField, field++) ? null : getRandIntervalDayTime(r); return field; }
From source file:org.apache.hadoop.io.TestArrayOutputStream.java
private void runComparison(ArrayOutputStream aos, DataOutputStream dos, ByteArrayOutputStream bos) throws IOException { Random r = new Random(); // byte//from www . j av a 2s . c o m int b = r.nextInt(128); aos.write(b); dos.write(b); // byte[] byte[] bytes = new byte[10]; r.nextBytes(bytes); aos.write(bytes, 0, 10); dos.write(bytes, 0, 10); // Byte aos.writeByte(b); dos.writeByte(b); // boolean boolean bool = r.nextBoolean(); aos.writeBoolean(bool); dos.writeBoolean(bool); // short short s = (short) r.nextInt(); aos.writeShort(s); dos.writeShort(s); // char int c = r.nextInt(); aos.writeChar(c); dos.writeChar(c); // int int i = r.nextInt(); aos.writeInt(i); dos.writeInt(i); // long long l = r.nextLong(); aos.writeLong(l); dos.writeLong(l); // float float f = r.nextFloat(); aos.writeFloat(f); dos.writeFloat(f); // double double d = r.nextDouble(); aos.writeDouble(d); dos.writeDouble(d); // strings String str = RandomStringUtils.random(20); aos.writeBytes(str); aos.writeChars(str); aos.writeUTF(str); dos.writeBytes(str); dos.writeChars(str); dos.writeUTF(str); byte[] expected = bos.toByteArray(); assertEquals(expected.length, aos.size()); byte[] actual = new byte[aos.size()]; System.arraycopy(aos.getBytes(), 0, actual, 0, actual.length); // serialized bytes should be the same assertTrue(Arrays.equals(expected, actual)); }
From source file:org.deeplearning4j.clustering.algorithm.BaseClusteringAlgorithm.java
/**Initialize the cluster centers at random *//* ww w. j a v a2 s .com*/ protected void initClusters() { log.info("Generating initial clusters"); List<Point> points = new ArrayList<>(initialPoints); //Initialize the ClusterSet with a single cluster center (based on position of one of the points chosen randomly) Random random = new Random(); clusterSet = new ClusterSet(clusteringStrategy.getDistanceFunction()); clusterSet.addNewClusterWithCenter(points.remove(random.nextInt(points.size()))); int initialClusterCount = clusteringStrategy.getInitialClusterCount(); //dxs: distances between each point and nearest cluster to that point INDArray dxs = Nd4j.create(points.size()); dxs.addi(Double.MAX_VALUE); //Generate the initial cluster centers, by randomly selecting a point between 0 and max distance //Thus, we are more likely to select (as a new cluster center) a point that is far from an existing cluster while (clusterSet.getClusterCount() < initialClusterCount && !points.isEmpty()) { dxs = ClusterUtils.computeSquareDistancesFromNearestCluster(clusterSet, points, dxs, exec); double r = random.nextFloat() * dxs.maxNumber().doubleValue(); for (int i = 0; i < dxs.length(); i++) { if (dxs.getDouble(i) >= r) { clusterSet.addNewClusterWithCenter(points.remove(i)); dxs = Nd4j.create(ArrayUtils.remove(dxs.data().asDouble(), i)); break; } } } ClusterSetInfo initialClusterSetInfo = ClusterUtils.computeClusterSetInfo(clusterSet); iterationHistory.getIterationsInfos().put(currentIteration, new IterationInfo(currentIteration, initialClusterSetInfo)); }
From source file:org.alfresco.module.org_alfresco_module_wcmquickstart.benchmark.RandomTextGenerator.java
/** * @param totalCharacters int// w w w .j a v a 2 s .co m * @param lineWidth int * @param enforceFullWord boolean * @return String */ public String generateText(int totalCharacters, int lineWidth, boolean enforceFullWord) { StringBuffer sb = new StringBuffer(); Random random = new Random(); CharQueue queue = new CharQueue(prefixLength); float weight = 0; queue.set(chain1.getBootstrapPrefix()); sb.append(queue.toString()); int width = 0; int c; do { String prefix = queue.toString(); // get a character from each chain c = chain1.get(prefix, random); int c2 = -1; if (chain2 != null) { c2 = chain2.get(prefix, random); } if (c == -1 && c2 == -1) { break; } // choose one if we can if (chain2 != null) { if (c == -1) { c = c2; } else if (c2 != -1 && random.nextFloat() < weight) { c = c2; } } sb.append((char) c); queue.put((char) c); width++; // line wrap if (c == ' ' && width > lineWidth) { sb.append("\n"); width = 0; } // go towards second markov chain weight += 1.0 / totalCharacters; } while (weight < 1 || (/*c != '.'*/Character.isLetter(c) && enforceFullWord)); sb.append("\n"); String generatedText = sb.toString(); return generatedText.substring(prefixLength + 1, prefixLength + 2).toUpperCase() + generatedText.substring(prefixLength + 2); }
From source file:com.alvermont.terraj.fracplanet.geom.TriangleMeshTerrain.java
private void doOneRiver(int r, Random random, boolean[] isSeaVertex, List<Set<Integer>> vertexNeighbours, int maxLakeSize) { int lastStallWarning = 0; final Set<Integer> verticesToAdd = new HashSet<Integer>(); final TreeMapMulti verticesToAddByHeight = new TreeMapMulti(); final Set<Integer> currentVertices = new HashSet<Integer>(); float currentVerticesHeight = 0; // start with a random non sea triangles final int sourceVertex = (int) (random.nextFloat() * getVertices().size()); if (!isSeaVertex[sourceVertex]) { currentVertices.add(sourceVertex); currentVerticesHeight = getVertexHeight(sourceVertex); while (true) { boolean reachedSea = false; final Set<Integer> currentVerticesNeighbours = new HashSet<Integer>(); for (int it : currentVertices) { verticesToAdd.add(it);/* w w w.j av a 2s . c o m*/ verticesToAddByHeight.insert(currentVerticesHeight, it); if (isSeaVertex[it]) { reachedSea = true; } final Set<Integer> neighbours = vertexNeighbours.get(it); for (int itN : neighbours) { if (!currentVertices.contains(itN)) { currentVerticesNeighbours.add(itN); } } } final TreeMapMulti flowCandidates = new TreeMapMulti(); for (int it : currentVerticesNeighbours) { flowCandidates.insert(getVertexHeight(it), it); } if (reachedSea) { break; } else if (currentVertices.size() >= maxLakeSize) { // lake becomes an inland sea if (log.isDebugEnabled()) { log.debug("River " + r + " is now an inland sea"); } break; } else { boolean meetsExisting = false; for (int it : currentVertices) { if (riverVertices.contains(it)) { meetsExisting = true; break; } } if (meetsExisting) { break; } } //debugPrintMap(flowCandidates); int numCurrentVertices = 0; if (flowCandidates.isEmpty()) { if (log.isDebugEnabled()) { log.warn("Unexpected internal state: no flow candidates " + "for river: " + r); } break; } else if (flowCandidates.getFirstHeight() < (currentVerticesHeight - getGeometry().epsilon())) { // log.debug("Flow downhill"); currentVertices.clear(); currentVerticesHeight = flowCandidates.getFirstHeight(); currentVertices.add(flowCandidates.getFirstVertex()); numCurrentVertices = 1; } else if (flowCandidates.getFirstHeight() < (currentVerticesHeight + getGeometry().epsilon())) { // log.debug("Expand across flat"); final SortedMap<Float, List<Integer>> subset = flowCandidates .headMap(currentVerticesHeight + getGeometry().epsilon()); for (List<Integer> list : subset.values()) { currentVertices.addAll(list); } numCurrentVertices = currentVertices.size(); } else { // log.debug("Raise level"); currentVerticesHeight = flowCandidates.getFirstHeight() + getGeometry().epsilon(); final int outflowVertex = flowCandidates.getFirstVertex(); currentVertices.add(outflowVertex); final SortedMap<Float, List<Integer>> subset = verticesToAddByHeight .headMap(currentVerticesHeight); for (List<Integer> list : subset.values()) { for (int vertex : list) { currentVertices.add(vertex); setVertexHeight(vertex, currentVerticesHeight); } } for (List<Integer> list : subset.values()) { list.clear(); } for (int it : currentVertices) { setVertexHeight(it, currentVerticesHeight); ++numCurrentVertices; } } if (numCurrentVertices >= (lastStallWarning + PROGRESS_STALL)) { final String msg = "Rivers (delay: " + numCurrentVertices + " vertex lake"; getProgress().progressStall(msg); } else if ((numCurrentVertices + PROGRESS_STALL) <= lastStallWarning) { final String msg = "Rivers: lake complete"; getProgress().progressStall(msg); lastStallWarning = numCurrentVertices; } } riverVertices.addAll(verticesToAdd); } }
From source file:com.gatf.executor.core.GatfFunctionHandler.java
public static String handleFunction(String function) { if (function.equals(BOOLEAN)) { Random rand = new Random(); return String.valueOf(rand.nextBoolean()); } else if (function.matches(DT_FMT_REGEX)) { Matcher match = datePattern.matcher(function); match.matches();//w w w. ja va 2 s. c om SimpleDateFormat format = new SimpleDateFormat(match.group(1)); return format.format(new Date()); } else if (function.matches(DT_FUNC_FMT_REGEX)) { Matcher match = specialDatePattern.matcher(function); match.matches(); String formatStr = match.group(1); String operation = match.group(2); int value = Integer.valueOf(match.group(3)); String unit = match.group(4); SimpleDateFormat format = new SimpleDateFormat(formatStr); try { Date dt = format.parse(format.format(new Date())); Calendar cal = Calendar.getInstance(); cal.setTime(dt); value = (operation.equals(MINUS) ? -value : value); if (unit.equals(YEAR)) { cal.add(Calendar.YEAR, value); } else if (unit.equals(MONTH)) { cal.add(Calendar.MONTH, value); } else if (unit.equals(DAY)) { cal.add(Calendar.DAY_OF_YEAR, value); } else if (unit.equals(HOUR)) { cal.add(Calendar.HOUR_OF_DAY, value); } else if (unit.equals(MINUITE)) { cal.add(Calendar.MINUTE, value); } else if (unit.equals(SECOND)) { cal.add(Calendar.SECOND, value); } else if (unit.equals(MILLISECOND)) { cal.add(Calendar.MILLISECOND, value); } return format.format(cal.getTime()); } catch (Exception e) { throw new AssertionError("Invalid date format specified - " + formatStr); } } else if (function.equals(FLOAT)) { Random rand = new Random(12345678L); return String.valueOf(rand.nextFloat()); } else if (function.equals(ALPHA)) { return RandomStringUtils.randomAlphabetic(10); } else if (function.equals(ALPHANUM)) { return RandomStringUtils.randomAlphanumeric(10); } else if (function.equals(NUMBER_PLUS)) { Random rand = new Random(); return String.valueOf(rand.nextInt(1234567)); } else if (function.equals(NUMBER_MINUS)) { Random rand = new Random(); return String.valueOf(-rand.nextInt(1234567)); } else if (function.equals(NUMBER)) { Random rand = new Random(); boolean bool = rand.nextBoolean(); return bool ? String.valueOf(rand.nextInt(1234567)) : String.valueOf(-rand.nextInt(1234567)); } else if (function.matches(RANDOM_RANGE_REGEX)) { Matcher match = randRangeNum.matcher(function); match.matches(); String min = match.group(1); String max = match.group(2); try { int nmin = Integer.parseInt(min); int nmax = Integer.parseInt(max); return String.valueOf(nmin + (int) (Math.random() * ((nmax - nmin) + 1))); } catch (Exception e) { e.printStackTrace(); } } return null; }
From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java
@Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Log.d(T, "onStartCommand()"); // Thread.setDefaultUncaughtExceptionHandler(new // CustomExceptionHandler()); ScanningAlarm.releaseWakeLock();//from w w w.j a v a 2s .c o m getWakeLock(this); // Register for broadcasts when discovery has finished registerDevicesReceiver(); float probability; if (intent != null && intent.getBooleanExtra(FORCED_BLUE_SCAN, true)) probability = 0; else { // get a random number Random r = new Random(System.currentTimeMillis()); probability = r.nextFloat(); } initiateScanningRound(probability); return START_STICKY; }
From source file:org.cloudsimulator.controller.ServiceMetricController.java
public String createServiceMetric() { XmlRdfCreator xmlRdfCreator = new XmlRdfCreator(); Random random = new Random(); createdXmlRdfServiceMetric = ""; this.okXmlRdf = false; for (GroupServiceMetric groupServiceMetric : groupServiceMetricList) { try {/*from www. j a v a 2 s .c om*/ Date dateFrom = new SimpleDateFormat(DATEFORMAT).parse(groupServiceMetric.getDateFrom() + ":00"); Date dateTo = new SimpleDateFormat(DATEFORMAT).parse(groupServiceMetric.getDateTo() + ":00"); Long period = (dateTo.getTime() - dateFrom.getTime()) / (groupServiceMetric.getNumberServiceMetric() + 1); Date currentDate = dateFrom; for (int i = 0; i < groupServiceMetric.getNumberServiceMetric(); i++) { currentDate = new Date(currentDate.getTime() + period); if ("".equals(createdXmlRdfServiceMetric)) { createdXmlRdfServiceMetric = xmlRdfCreator.createServiceMetricXmlRdf(new ServiceMetric( Utility.convertDateToString(DATEFORMAT, currentDate), groupServiceMetric.getMetricName(), random.nextFloat() * (groupServiceMetric.getMaxValue() - groupServiceMetric.getMinValue()) + groupServiceMetric.getMinValue(), groupServiceMetric.getMetricUnit(), groupServiceMetric.getDependsOn())); } else { createdXmlRdfServiceMetric = new StringBuilder(createdXmlRdfServiceMetric).insert( createdXmlRdfServiceMetric.length() - 12, xmlRdfCreator.createServiceMetricXmlRdfWithoutRDFElement(new ServiceMetric( Utility.convertDateToString(DATEFORMAT, currentDate), groupServiceMetric.getMetricName(), random.nextFloat() * (groupServiceMetric.getMaxValue() - groupServiceMetric.getMinValue()) + groupServiceMetric.getMinValue(), groupServiceMetric.getMetricUnit(), groupServiceMetric.getDependsOn()))) .toString(); } } createdXmlRdfServiceMetric = new StringBuilder(createdXmlRdfServiceMetric) .insert(createdXmlRdfServiceMetric.length() - 12, xmlRdfCreator.createServiceMetricXmlRdfWithoutRDFElement(new ServiceMetric( Utility.convertDateToString(DATEFORMAT, new Date(currentDate.getTime() + period)), groupServiceMetric.getMetricName(), groupServiceMetric.getFinalValue(), groupServiceMetric.getMetricUnit(), groupServiceMetric.getDependsOn()))) .toString(); } catch (RuntimeException e) { LOGGER.error(e.getMessage(), e); this.errorMessage = e.toString(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); this.errorMessage = e.toString(); } } this.okXmlRdf = true; return "visualizeXMLServiceMetric"; }
From source file:org.gofleet.module.routing.RoutingMap.java
private void processTSPPlan(TSPPlan[] res, JProgressBar progressBar) { Random random = new Random(); try {// ww w .java2 s . c o m @SuppressWarnings("unchecked") Collection<Layer> allLayers = Collections.unmodifiableCollection(this.mapView.getAllLayers()); List<Layer> toremove = new LinkedList<Layer>(); for (Layer l : allLayers) { if (l.name.startsWith("Route Plan") || l.name.startsWith("Stops")) toremove.add(l); } for (Layer l : toremove) this.mapView.removeLayer(l); LatLon latlon_origin = null; int id_layer = 0; for (TSPPlan plan : res) { latlon_origin = new LatLon(plan.getOrigin()[1], plan.getOrigin()[0]); log.info(latlon_origin); LineElemStyle ls = new LineElemStyle(); float f = random.nextFloat(); ls.color = Color.getHSBColor(f * random.nextFloat(), 0.9f, 0.9f); ls.width = LogicConstants.getInt("PLAN_WAY_WIDTH", 2); MarkerLayer stops = new MarkerLayer(new GpxData(), "Stops " + id_layer, File.createTempFile("stops", "tmp"), new GpxLayer(new GpxData()), this.mapView); stops.data.add(new StopMarker(latlon_origin, "origin", "tsp_stop", stops, 0, 0, ls.color)); for (String stop : plan.getStops()) { String[] array = stop.split(","); double[] point = new double[2]; point[1] = new Double(array[0]); point[0] = new Double(array[1]); LatLon ll = new LatLon(point[0], point[1]); log.info(ll); stops.data.add(new StopMarker(ll, array[2], "tsp_stop", stops, 0, 0, ls.color)); } this.mapView.addLayer(stops, true); OsmDataLayer layer = new OsmDataLayer(new DataSet(), "Route Plan " + id_layer++, File.createTempFile("planning", "route")); String way2 = plan.getWay(); if (way2 != null) { Way way = new Way(); LatLon info = null; MultiLineString multilinestring = (MultiLineString) wktReader.read(way2); multilinestring.getLength(); int numGeometries = multilinestring.getNumGeometries(); for (int i = 0; i < numGeometries; i++) { for (Coordinate coordenada : multilinestring.getGeometryN(i).getCoordinates()) { LatLon ll = new LatLon(coordenada.y, coordenada.x); way.addNode(new Node(ll)); if (info == null) info = ll; } way.mappaintStyle = ls; layer.data.ways.add(way); way = new Way(); } progressBar.setValue(progressBar.getValue() + 1); StopMarker marker = new StopMarker(info, (new Double(plan.getDistance())).toString().substring(0, 5) + " km in " + (new Double(plan.getTime() / 60)).toString().substring(0, 3) + " hours", "tsp_stop", stops, 0, 0, ls.color); marker.setPaintIcon(false); stops.data.add(marker); } this.mapView.addLayer(layer, true); layer.visible = true; stops.visible = true; } } catch (Throwable e) { log.error("Error painting plan", e); } }
From source file:org.apache.flink.table.codegen.SortCodeGeneratorTest.java
private Object[] generateValues(InternalType type) { Random rnd = new Random(); int seedNum = RECORD_NUM / 5; Object[] seeds = new Object[seedNum]; seeds[0] = null;//from w w w. jav a 2 s . c o m seeds[1] = value1(type, rnd); seeds[2] = value2(type, rnd); seeds[3] = value3(type, rnd); for (int i = 4; i < seeds.length; i++) { if (type.equals(InternalTypes.BOOLEAN)) { seeds[i] = rnd.nextBoolean(); } else if (type.equals(InternalTypes.BYTE)) { seeds[i] = (byte) rnd.nextLong(); } else if (type.equals(InternalTypes.SHORT)) { seeds[i] = (short) rnd.nextLong(); } else if (type.equals(InternalTypes.INT)) { seeds[i] = rnd.nextInt(); } else if (type.equals(InternalTypes.LONG)) { seeds[i] = rnd.nextLong(); } else if (type.equals(InternalTypes.FLOAT)) { seeds[i] = rnd.nextFloat() * rnd.nextLong(); } else if (type.equals(InternalTypes.DOUBLE)) { seeds[i] = rnd.nextDouble() * rnd.nextLong(); } else if (type.equals(InternalTypes.STRING)) { seeds[i] = BinaryString.fromString(RandomStringUtils.random(rnd.nextInt(20))); } else if (type instanceof DecimalType) { DecimalType decimalType = (DecimalType) type; BigDecimal decimal = new BigDecimal(rnd.nextInt()).divide( new BigDecimal(ThreadLocalRandom.current().nextInt(1, 256)), ThreadLocalRandom.current().nextInt(1, 30), BigDecimal.ROUND_HALF_EVEN); seeds[i] = Decimal.fromBigDecimal(decimal, decimalType.precision(), decimalType.scale()); } else if (type instanceof ArrayType || type.equals(InternalTypes.BINARY)) { byte[] bytes = new byte[rnd.nextInt(16) + 1]; rnd.nextBytes(bytes); seeds[i] = type.equals(InternalTypes.BINARY) ? bytes : BinaryArray.fromPrimitiveArray(bytes); } else if (type instanceof RowType) { RowType rowType = (RowType) type; if (rowType.getTypeAt(0).equals(InternalTypes.INT)) { seeds[i] = GenericRow.of(rnd.nextInt()); } else { seeds[i] = GenericRow.of(GenericRow.of(rnd.nextInt())); } } else if (type instanceof GenericType) { seeds[i] = new BinaryGeneric<>(rnd.nextInt(), IntSerializer.INSTANCE); } else { throw new RuntimeException("Not support!"); } } // result values Object[] results = new Object[RECORD_NUM]; for (int i = 0; i < RECORD_NUM; i++) { results[i] = seeds[rnd.nextInt(seedNum)]; } return results; }