List of usage examples for java.util Random nextDouble
public double nextDouble()
From source file:com.mapr.synth.drive.DriveTest.java
@Test public void testPlanning() throws FileNotFoundException { Random rand = new Random(3); GeoPoint start = new GeoPoint((rand.nextDouble() - 0.5) * Math.PI / 2, rand.nextDouble() * Math.PI * 2); GeoPoint end = start.nearby(10, rand); Vector3D east = start.east(); Vector3D north = start.north(east); try (PrintWriter out = new PrintWriter(new File("short-drive.csv"))) { out.printf("i, highway, x0, y0, x1, y1"); double highway = 0; int n = 0; for (int i = 0; i < 50; i++) { List<Car.Segment> plan = Car.plan(start, end, rand); assertTrue(plan.size() < 20); Vector3D here = project(east, north, start.as3D()); for (Car.Segment segment : plan) { Vector3D step = project(east, north, segment.getEnd().as3D()); n++;/*from w w w . j a v a2 s .c om*/ if (segment instanceof Car.Highway) { highway++; } out.printf("%d, %d, %.4f, %.4f, %.4f, %.4f\n", i, (segment instanceof Car.Local) ? 1 : 0, here.getX(), here.getY(), step.getX(), step.getY()); here = step; } // should arrive at our destination! assertEquals(0.0, here.subtract(project(east, north, end.as3D())).getNorm(), 0.01); } // most steps should be local, not highway assertEquals(0.0, highway / n, 0.1); } }
From source file:pl.mg6.newmaps.demo.ManyMarkersExampleActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.many_markers_example); GoogleMap map = GoogleMapHelper.getMap(this, R.id.many_markers_map); Random r = new Random(); long start = SystemClock.uptimeMillis(); for (int i = 0; i < MARKERS_COUNT; i++) { LatLng position = new LatLng((r.nextDouble() - 0.5) * 170.0, (r.nextDouble() - 0.5) * 360.0); map.addMarker(new MarkerOptions().position(position)); }/*from w ww . j a v a 2 s . com*/ long end = SystemClock.uptimeMillis(); Log.w(TAG, "addMarkers time: " + (end - start)); }
From source file:com.mapr.synth.drive.DriveTest.java
@Test public void testDriving() throws FileNotFoundException { Random rand = new Random(3); GeoPoint start = new GeoPoint((rand.nextDouble() - 0.5) * Math.PI / 2, rand.nextDouble() * Math.PI * 2); GeoPoint end = start.nearby(10, rand); final Vector3D east = start.east(); final Vector3D north = start.north(east); try (PrintWriter out = new PrintWriter(new File("drive-sim.csv"))) { out.printf("i, t, x, y, rpm, throttle, speed, gear"); for (int i = 0; i < 50; i++) { final int trial = i; double t = 0; Car car = new Car(); List<Car.Segment> plan = Car.plan(start, end, rand); assertTrue(plan.size() < 20); final GeoPoint currentPosition = new GeoPoint(start.as3D()); for (Car.Segment segment : plan) { t = car.simulate(t, currentPosition, rand, segment, new Car.Callback() { @Override/* w w w. jav a 2 s . c o m*/ void call(double t, Engine arg, GeoPoint position) { final Vector3D here = project(east, north, currentPosition.as3D()); Engine engine = car.getEngine(); out.printf("%d, %.2f, %.2f, %.2f, %.1f, %.1f, %.1f, %d\n", trial, t, here.getX(), here.getY(), engine.getRpm(), engine.getThrottle(), engine.getSpeed(), engine.getGear()); } }); assertEquals(0, currentPosition.distance(segment.getEnd()), 0.04); } // should arrive at our destination! assertEquals(0.0, currentPosition.distance(end), 0.01); } } }
From source file:fll.web.playoff.Playoff.java
/** * Build the list of teams ordered from top to bottom (visually) of a single * elimination bracket./*w ww .j a v a2 s . c o m*/ * * @param connection connection to the database * @param teams the teams in the playoffs * @return a List of teams * @throws SQLException on a database error */ public static List<Team> buildInitialBracketOrder(final Connection connection, final BracketSortType bracketSort, final WinnerType winnerCriteria, final List<? extends Team> teams) throws SQLException { if (null == connection) { throw new NullPointerException("Connection cannot be null"); } final List<? extends Team> seedingOrder; if (BracketSortType.ALPHA_TEAM == bracketSort) { seedingOrder = teams; // sort by team name Collections.sort(seedingOrder, Team.TEAM_NAME_COMPARATOR); } else if (BracketSortType.RANDOM == bracketSort) { seedingOrder = teams; // assign a random number to each team final double[] randoms = new double[seedingOrder.size()]; final Random generator = new Random(); for (int i = 0; i < randoms.length; ++i) { randoms[i] = generator.nextDouble(); } Collections.sort(seedingOrder, new Comparator<Team>() { public int compare(final Team one, final Team two) { final int oneIdx = seedingOrder.indexOf(one); final int twoIdx = seedingOrder.indexOf(two); return Double.compare(randoms[oneIdx], randoms[twoIdx]); } }); } else { // standard seeding final int tournament = Queries.getCurrentTournament(connection); final int numSeedingRounds = TournamentParameters.getNumSeedingRounds(connection, tournament); if (numSeedingRounds < 1) { throw new FLLRuntimeException( "Cannot initialize playoff brackets using scores from seeding rounds when the number of seeing rounds is less than 1"); } seedingOrder = Queries.getPlayoffSeedingOrder(connection, winnerCriteria, teams); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("seedingOrder: " + seedingOrder); } final int[] seeding = computeInitialBrackets(seedingOrder.size()); // give byes to the last byesNeeded teams. final List<Team> list = new LinkedList<Team>(); for (final int element : seeding) { if (element > seedingOrder.size()) { list.add(Team.BYE); } else { final Team team = seedingOrder.get(element - 1); list.add(team); } } if (list.size() != seeding.length) { throw new InternalError("Programming error, list size should be the same as seeding length"); } return list; }
From source file:com.facebook.LinkBench.distributions.ZipfDistribution.java
/** * Algorithm from "Quickly Generating Billion-Record Synthetic Databases", * Gray et. al., 1994//from ww w . j ava 2 s. c om * * Pick a value in range [min, max) according to zipf distribution, * with min being the most likely to be chosen */ @Override public long choose(Random rng) { return quantile(rng.nextDouble()); }
From source file:com.twitter.graphjet.bipartite.edgepool.EdgePoolConcurrentTestHelper.java
/** * This helper method sets up a concurrent read-write situation with a single writer and multiple * readers that access the same underlying edgePool, and tests for correct edge access during * simultaneous edge writes. This helps test read consistency during arbitrary points of * inserting edges. Note that the exact read-write sequence here is non-deterministic and would * vary depending on the machine, but the hope is that given the large number of readers the reads * would be done at many different points of edge insertion. The test itself checks only for * partial correctness (it could have false positives) so this should only be used as a supplement * to other testing.//from www.ja va2 s .c o m * * @param edgePool is the underlying * {@link com.twitter.graphjet.bipartite.edgepool.EdgePool} * @param numReadersPerNode is the number of reader threads to use per node * @param leftSize is the number of left nodes * @param rightSize is the number of right nodes * @param edgeProbability is the probability of an edge between a left-right node pair * @param random is the random number generator to use for generating a random graph */ public static void testRandomConcurrentReadWriteThreads(EdgePool edgePool, int numReadersPerNode, int leftSize, int rightSize, double edgeProbability, Random random) { int maxWaitingTimeForThreads = 20; // in milliseconds int numReaders = leftSize * numReadersPerNode; CountDownLatch readersDoneLatch = new CountDownLatch(numReaders); // First, construct a random set of edges to insert in the graph Set<Pair<Integer, Integer>> edges = Sets .newHashSetWithExpectedSize((int) (leftSize * rightSize * edgeProbability)); List<EdgePoolReader> readers = Lists.newArrayListWithCapacity(numReaders); Int2ObjectMap<IntSet> leftSideGraph = new Int2ObjectOpenHashMap<IntSet>(leftSize); int averageLeftDegree = (int) (rightSize * edgeProbability); for (int i = 0; i < leftSize; i++) { IntSet nodeEdges = new IntOpenHashSet(averageLeftDegree); for (int j = 0; j < rightSize; j++) { if (random.nextDouble() < edgeProbability) { nodeEdges.add(j); edges.add(Pair.of(i, j)); } } leftSideGraph.put(i, nodeEdges); } // Create a bunch of leftReaders per node that'll read from the graph at random for (int i = 0; i < leftSize; i++) { for (int j = 0; j < numReadersPerNode; j++) { readers.add(new EdgePoolReader(edgePool, new CountDownLatch(0), readersDoneLatch, i, random.nextInt(maxWaitingTimeForThreads))); } } // Create a single writer that will insert these edges in random order List<WriterInfo> writerInfo = Lists.newArrayListWithCapacity(edges.size()); List<Pair<Integer, Integer>> edgesList = Lists.newArrayList(edges); Collections.shuffle(edgesList); CountDownLatch writerDoneLatch = new CountDownLatch(edgesList.size()); for (Pair<Integer, Integer> edge : edgesList) { writerInfo.add(new WriterInfo(edge.getLeft(), edge.getRight(), new CountDownLatch(0), writerDoneLatch)); } ExecutorService executor = Executors.newFixedThreadPool(numReaders + 1); // single writer List<Callable<Integer>> allThreads = Lists.newArrayListWithCapacity(numReaders + 1); // First, we add the writer allThreads.add(Executors.callable(new EdgePoolWriter(edgePool, writerInfo), 1)); // then the readers for (int i = 0; i < numReaders; i++) { allThreads.add(Executors.callable(readers.get(i), 1)); } // these will execute in some non-deterministic order Collections.shuffle(allThreads, random); // Wait for all the processes to finish try { List<Future<Integer>> results = executor.invokeAll(allThreads, 10, TimeUnit.SECONDS); for (Future<Integer> result : results) { assertTrue(result.isDone()); assertEquals(1, result.get().intValue()); } } catch (InterruptedException e) { throw new RuntimeException("Execution for a thread was interrupted: ", e); } catch (ExecutionException e) { throw new RuntimeException("Execution issue in an executor thread: ", e); } // confirm that these worked as expected try { readersDoneLatch.await(); writerDoneLatch.await(); } catch (InterruptedException e) { throw new RuntimeException("Execution for last reader was interrupted: ", e); } // Check that all readers' read info is consistent with the graph for (EdgePoolReader reader : readers) { IntSet expectedEdges = leftSideGraph.get(reader.queryNode); assertTrue(reader.getQueryNodeDegree() <= expectedEdges.size()); if (reader.getQueryNodeDegree() == 0) { assertNull(reader.getQueryNodeEdges()); } else { for (int edge : reader.getQueryNodeEdges()) { assertTrue(expectedEdges.contains(edge)); } } } }
From source file:markov_chain.model.NormalizedGenerator.java
private State<T> chooseNextState(State<T> state, int position) throws MathException { Random rand = new Random(); double probabilityOfCompleation = dist.cumulativeProbability(position); if (probabilityOfCompleation > rand.nextDouble()) { return std.getGuard(); }/* ww w. ja va2s.c om*/ int count = rand.nextInt(state.transitionCount + 1); State<T> nextState = null; for (Entry<T, Integer> entry : state.transitions.entrySet()) { count -= entry.getValue(); if (count <= 0) { nextState = std.getState(entry.getKey()); break; } } if (nextState == null) { // current state has no transitions so we force an end nextState = std.getGuard(); } return nextState; }
From source file:org.grouplens.samantha.modeler.featurizer.PercentileModel.java
public PercentileModel buildModel(String attrName, int numValues, EntityDAO entityDAO) { RealVector values = MatrixUtils.createRealVector(new double[dim]); Double2IntSortedMap sortedMap = new Double2IntAVLTreeMap(); int total = 0; Random random = new Random(); while (entityDAO.hasNextEntity()) { if (random.nextDouble() > sampleRate) { entityDAO.getNextEntity();//from w w w. j a v a 2 s. c om continue; } double value = entityDAO.getNextEntity().get(attrName).asDouble(); if (sortedMap.containsKey(value)) { sortedMap.put(value, sortedMap.get(value) + 1); } else { sortedMap.put(value, 1); } total++; } values.setEntry(0, numValues); int idx = 0; int cnt = 0; for (Double2IntMap.Entry entry : sortedMap.double2IntEntrySet()) { double key = entry.getDoubleKey(); int num = entry.getIntValue(); cnt += num; double value = cnt * 1.0 / total; double point = idx * 1.0 / numValues; while (point <= value) { values.setEntry(idx * 2 + 1, key); values.setEntry(idx * 2 + 2, point); idx++; point = idx * 1.0 / numValues; } } ensureKey(attrName); setKeyVector(attrName, values); return this; }
From source file:com.cburch.draw.shapes.Line.java
@Override public Location getRandomPoint(Bounds bds, Random rand) { double u = rand.nextDouble(); int x = (int) Math.round(x0 + u * (x1 - x0)); int y = (int) Math.round(y0 + u * (y1 - y0)); int w = strokeWidth; if (w > 1) { x += (rand.nextInt(w) - w / 2);/*from w w w . j a v a 2s. co m*/ y += (rand.nextInt(w) - w / 2); } return Location.create(x, y); }
From source file:ro.hasna.ts.math.representation.IndexableSymbolicAggregateApproximationTest.java
@Test public void testTransformToSaxPairArray3() throws Exception { double[] list = new double[64]; Random random = new Random(); for (int i = 0; i < 26; i++) { list[i] = random.nextDouble(); }/*from w w w .j a v a 2s . c om*/ for (int i = 26; i < 40; i++) { list[i] = 20 + random.nextDouble(); } for (int i = 40; i < 64; i++) { list[i] = random.nextDouble(); } int[] alphabetSizes = { 2, 2, 2, 4, 4, 2, 2, 2 }; SaxPair[] expected = new SaxPair[8]; expected[0] = new SaxPair(0, 2); expected[1] = new SaxPair(0, 2); expected[2] = new SaxPair(0, 2); expected[3] = new SaxPair(3, 4); expected[4] = new SaxPair(3, 4); expected[5] = new SaxPair(0, 2); expected[6] = new SaxPair(0, 2); expected[7] = new SaxPair(0, 2); IndexableSymbolicAggregateApproximation isax = new IndexableSymbolicAggregateApproximation(8, alphabetSizes); SaxPair[] result = isax.transform(list); Assert.assertArrayEquals(expected, result); }