List of usage examples for java.util Random nextDouble
public double nextDouble()
From source file:acromusashi.stream.ml.clustering.kmeans.KmeansCalculator.java
/** * KMeans++?????//from ww w . ja va2 s .c o m * * @param basePoints ?? * @param clusterNum * @return */ public static List<KmeansPoint> createInitialCentroids(List<KmeansPoint> basePoints, int clusterNum) { Random random = new Random(); List<KmeansPoint> resultList = Lists.newArrayList(); // ?????????? List<KmeansPoint> pointList = Lists.newArrayList(basePoints); KmeansPoint firstCentroid = pointList.remove(random.nextInt(pointList.size())); resultList.add(firstCentroid); double[] dxs; // KMeans++?????? // ??1????????1???? for (int centroidIndex = 1; centroidIndex < clusterNum; centroidIndex++) { // ????????????? dxs = computeDxs(pointList, resultList); // ?????????? double r = random.nextDouble() * dxs[dxs.length - 1]; int next = Arrays.binarySearch(dxs, r); int index = 0; if (next > 0) { index = next - 1; } else if (next < 0) { index = COMPENSATE_INDEX - next; } while (index > 0 && resultList.contains(pointList.get(index))) { index = index - 1; } resultList.add(pointList.get(index)); } return resultList; }
From source file:eu.crisis_economics.abm.markets.clearing.heterogeneous.LineSearchTest.java
@Test /**/* ww w.j a v a2s.c o m*/ * Test the Brent line search algorithm by minimizing a multidimensional * quadratic scalar function. This test generates many random quadratic * fields with random global minima. In each case, the starting point * of the minimization is random and the line search direction points * toward the global minimum. */ public void batchTestMultidimensionalQuadraticLineSearch() { final Random dice = new Random(); for (int i = 0; i < 100; ++i) { // 100 random quadratic minimization tests final int numDimensions = dice.nextInt(20) + 2; final double[] globalMinimum = new double[numDimensions], startingPoint = new double[numDimensions]; for (int j = 0; j < globalMinimum.length; ++j) { globalMinimum[j] = dice.nextDouble() * 10. - 5.; startingPoint[j] = dice.nextDouble() * 10. - 5.; } testMultiDimensionalQuadraticMinimization(numDimensions, startingPoint, globalMinimum); } }
From source file:net.thumbtack.test.client.JsonQueryClientThread.java
public JsonQueryClientThread(CouchbaseClient _client, GlobalConfig config, long _insertStart, long _insertEnd) { this.client = _client; this.operationCount = config.getOperationCount(); this.insertStart = _insertStart; this.insertEnd = _insertEnd; this.pageSize = config.getPageSize(); this.queryIndex = config.getQueryIndex(); this.pageNumber = config.getPageNumber(); OperationType operationType = config.getOperationType(); switch (operationType) { case INSERT: { func = new Func() { public void run() throws JsonProcessingException { for (long i = insertStart; i < insertEnd; i++) { VendorDoc vendorDoc = new VendorDoc(i); long time = System.currentTimeMillis(); client.insert(String.valueOf(i), om.writeValueAsString(vendorDoc)); respTimes.add(time - System.currentTimeMillis()); }//www . j a v a 2 s. co m } }; break; } case READ: { func = new Func() { public void run() { Random randomKey = new Random(); for (int i = 0; i < operationCount; i++) { long time = System.currentTimeMillis(); client.read(String .valueOf((int) (randomKey.nextDouble() * (insertEnd - insertStart) + insertStart))); respTimes.add(time - System.currentTimeMillis()); } } }; break; } case UPDATE: { func = new Func() { public void run() throws JsonProcessingException { Random randomKey = new Random(); for (long i = 0; i < operationCount; i++) { VendorDoc vendorDoc = new VendorDoc(i); long time = System.currentTimeMillis(); client.update( String.valueOf( (int) (randomKey.nextDouble() * (insertEnd - insertStart) + insertStart)), om.writeValueAsString(vendorDoc)); respTimes.add(time - System.currentTimeMillis()); } } }; break; } case QUERY: { func = new Func() { public void run() throws JsonProcessingException { Random randomKey = new Random(); for (long i = 0; i < operationCount; i++) { int viewIndex = queryIndex != -1 ? queryIndex : (int) (randomKey.nextDouble() * viewNames.length); int page = pageNumber != -1 ? pageNumber : (int) (randomKey.nextDouble() * 100); long timeElasped; Object key = getViewKey(viewIndex); if (viewIndex < 3) { timeElasped = client.searchInView(viewNames[viewIndex], key, true, pageSize, page); } else { timeElasped = client.searchInSortedView(viewNames[viewIndex], key, true, pageSize, page); } respTimes.add(timeElasped); } } }; break; } case N1QL: { func = new Func() { public void run() throws JsonProcessingException { Random randomKey = new Random(); for (long i = 0; i < operationCount; i++) { int viewIndex = queryIndex != -1 ? queryIndex : (int) (randomKey.nextDouble() * queries.length); long timeElasped = client.searchN1QL(getN1qlQuery(viewIndex) + " limit " + pageSize); respTimes.add(timeElasped); } } }; break; } default: { throw new UnsupportedOperationException(operationType.toString()); } } }
From source file:se.llbit.math.Ray.java
/** * Scatter ray normal/*from w ww . j a v a 2s . c om*/ * @param random random number source */ public final void scatterNormal(Random random) { // get random point on unit disk double x1 = random.nextDouble(); double x2 = random.nextDouble(); double r = FastMath.sqrt(x1); double theta = 2 * Math.PI * x2; // project to point on hemisphere in tangent space double tx = r * FastMath.cos(theta); double ty = r * FastMath.sin(theta); double tz = FastMath.sqrt(1 - x1); // transform from tangent space to world space double xx, xy, xz; double ux, uy, uz; double vx, vy, vz; if (QuickMath.abs(n.x) > .1) { xx = 0; xy = 1; xz = 0; } else { xx = 1; xy = 0; xz = 0; } ux = xy * n.z - xz * n.y; uy = xz * n.x - xx * n.z; uz = xx * n.y - xy * n.x; r = 1 / FastMath.sqrt(ux * ux + uy * uy + uz * uz); ux *= r; uy *= r; uz *= r; vx = uy * n.z - uz * n.y; vy = uz * n.x - ux * n.z; vz = ux * n.y - uy * n.x; n.set(ux * tx + vx * ty + n.x * tz, uy * tx + vy * ty + n.y * tz, uz * tx + vz * ty + n.z * tz); }
From source file:se.llbit.chunky.renderer.scene.Sun.java
/** * Point ray in random direction within sun solid angle * @param reflected/*from w ww . j a v a 2 s .c om*/ * @param random */ public void getRandomSunDirection(Ray reflected, Random random) { double x1 = random.nextDouble(); double x2 = random.nextDouble(); double cos_a = 1 - x1 + x1 * RADIUS_COS; double sin_a = FastMath.sqrt(1 - cos_a * cos_a); double phi = 2 * Math.PI * x2; Vector3d u = new Vector3d(su); Vector3d v = new Vector3d(sv); Vector3d w = new Vector3d(sw); u.scale(FastMath.cos(phi) * sin_a); v.scale(FastMath.sin(phi) * sin_a); w.scale(cos_a); reflected.d.add(u, v); reflected.d.add(w); reflected.d.normalize(); }
From source file:eu.crisis_economics.abm.markets.clearing.heterogeneous.LineSearchTest.java
@Test /**/* w w w. j av a2 s.c o m*/ * Test the Brent line search algorithm by minimizing a negative * multidimensional quadratic scalar function, with maximum at the * origin. This test generated many random boundary boxes (limits * inside of which to perform line searches) and, in each case, * extremizes the quadratic function along a random direction starting * at the origin. It is expected that the solution lies on the domain * bounds in each case. */ public void batchTestBoundedDecreasingMultidimensionalSearch() { final Random dice = new Random(); for (int i = 0; i < 100; ++i) { // 100 random tests final int numDimensions = dice.nextInt(20) + 2; final double[] lowerDomainBounds = new double[numDimensions], upperDomainBounds = new double[numDimensions]; for (int j = 0; j < numDimensions; ++j) { lowerDomainBounds[j] = -dice.nextDouble(); upperDomainBounds[j] = +dice.nextDouble(); } testOptimizationWithDomainBounds(numDimensions, lowerDomainBounds, upperDomainBounds); } }
From source file:com.facebook.presto.operator.aggregation.AbstractTestApproximateAggregationFunction.java
private void testCorrectnessOfErrorFunction(List<Number> inputList) throws Exception { int inRange = 0; int numberOfRuns = 1000; double sampleRatio = 1 / (double) WEIGHT; double actual = getExpectedValue(inputList); Random rand = new Random(1); for (int i = 0; i < numberOfRuns; i++) { //Compute Sampled Value using sampledList (numberOfRuns times) ImmutableList.Builder<Number> sampledList = ImmutableList.builder(); for (Number x : inputList) { if (rand.nextDouble() < sampleRatio) { sampledList.add(x);//w w w . j a v a 2 s .c o m } } ImmutableList<Number> list = sampledList.build(); BlockBuilder builder = getType().createBlockBuilder(new BlockBuilderStatus(), list.size()); for (Number sample : list) { if (getType().equals(BIGINT)) { BIGINT.writeLong(builder, sample.longValue()); } else if (getType().equals(DOUBLE)) { DOUBLE.writeDouble(builder, sample.doubleValue()); } else { throw new AssertionError("Can only handle longs and doubles"); } } Page page = new Page(builder.build()); page = OperatorAssertion.appendSampleWeight(ImmutableList.of(page), WEIGHT).get(0); Accumulator accumulator = getFunction().bind(ImmutableList.of(0), Optional.empty(), Optional.of(page.getChannelCount() - 1), getConfidence()).createAccumulator(); accumulator.addInput(page); Block result = getFinalBlock(accumulator); String approxValue = BlockAssertions.toValues(accumulator.getFinalType(), result).get(0).toString(); double approx = Double.parseDouble(approxValue.split(" ")[0]); double error = Double.parseDouble(approxValue.split(" ")[2]); //Check if actual answer lies within [approxAnswer - error, approxAnswer + error] if (Math.abs(approx - actual) <= error) { inRange++; } } BinomialDistribution binomial = new BinomialDistribution(numberOfRuns, getConfidence()); int lowerBound = binomial.inverseCumulativeProbability(0.01); int upperBound = binomial.inverseCumulativeProbability(0.99); assertTrue(lowerBound < inRange && inRange < upperBound, String .format("%d out of %d passed. Expected [%d, %d]", inRange, numberOfRuns, lowerBound, upperBound)); }
From source file:org.perfcake.reporting.destinations.ChartDestinationTest.java
@Test public void basicTest() throws Exception { final String tempDir = "target/chart";//TestSetup.createTempDir("test-chart"); log.info("Created temp directory for chart: " + tempDir); final ChartDestination cd = new ChartDestination(); final ChartDestination cd2 = new ChartDestination(); cd.setOutputDir(tempDir);/*ww w . j a v a 2 s.c o m*/ cd2.setOutputDir(tempDir); cd.setXAxis("Time of test"); cd2.setXAxis("Time of test"); cd.setYAxis("Iterations per second"); cd2.setYAxis("Iterations per second"); cd2.setxAxisType(PeriodType.ITERATION); cd.setName("Statistics " + (new SimpleDateFormat("HHmmss")).format(new Date())); cd2.setName("Performance " + (new SimpleDateFormat("HHmmss")).format(new Date())); cd.setGroup("stats"); cd2.setGroup("perf"); cd.setAttributes("Average, Result"); cd2.setAttributes("Average, Result"); cd.open(); cd2.open(); long base = System.currentTimeMillis(); final Random rnd = new Random(); Measurement m = new Measurement(10, System.currentTimeMillis() - base, 1); m.set(10.3 + rnd.nextDouble()); m.set("Average", 9.8 + rnd.nextDouble()); m.set("warmUp", true); cd.report(m); cd2.report(m); Thread.sleep(100); m = new Measurement(10, System.currentTimeMillis() - base, 2); m.set(10.3 + rnd.nextDouble()); m.set("Average", 9.8 + rnd.nextDouble()); m.set("warmUp", true); cd.report(m); cd2.report(m); Thread.sleep(100); m = new Measurement(10, System.currentTimeMillis() - base, 3); m.set(10.3 + rnd.nextDouble()); m.set("Average", 9.8 + rnd.nextDouble()); m.set("warmUp", true); cd.report(m); cd2.report(m); Thread.sleep(100); base = System.currentTimeMillis(); m = new Measurement(10, System.currentTimeMillis() - base, 1); m.set(10.3 + rnd.nextDouble()); m.set("Average", 9.8 + rnd.nextDouble()); m.set("warmUp", false); cd.report(m); cd2.report(m); Thread.sleep(100); m = new Measurement(13, System.currentTimeMillis() - base, 2); m.set(11.1 + rnd.nextDouble()); m.set("Average", 9.1 + rnd.nextDouble()); m.set("warmUp", false); cd.report(m); cd2.report(m); Thread.sleep(2000); m = new Measurement(100, System.currentTimeMillis() - base, 10); m.set(9.2 + rnd.nextDouble()); m.set("Average", 9.0 + rnd.nextDouble()); m.set("warmUp", false); cd.report(m); cd2.report(m); cd.close(); cd2.close(); final Path dir = Paths.get(tempDir); verifyBasicFiles(Paths.get(tempDir)); Assert.assertTrue(dir .resolve(Paths.get("data", "stats" + System.getProperty(PerfCakeConst.NICE_TIMESTAMP_PROPERTY) + ".js")) .toFile().exists()); Assert.assertTrue(dir .resolve(Paths.get("data", "stats" + System.getProperty(PerfCakeConst.NICE_TIMESTAMP_PROPERTY) + ".dat")) .toFile().exists()); Assert.assertTrue(dir .resolve(Paths.get("data", "stats" + System.getProperty(PerfCakeConst.NICE_TIMESTAMP_PROPERTY) + ".html")) .toFile().exists()); Assert.assertTrue(dir .resolve(Paths.get("data", "perf" + System.getProperty(PerfCakeConst.NICE_TIMESTAMP_PROPERTY) + ".js")) .toFile().exists()); Assert.assertTrue(dir .resolve(Paths.get("data", "perf" + System.getProperty(PerfCakeConst.NICE_TIMESTAMP_PROPERTY) + ".dat")) .toFile().exists()); Assert.assertTrue(dir .resolve(Paths.get("data", "perf" + System.getProperty(PerfCakeConst.NICE_TIMESTAMP_PROPERTY) + ".html")) .toFile().exists()); }
From source file:org.berlin.batch.bom.DataMessageFinder.java
public List<String> queryConnectRules() { // First, a random selection to determine which rule to use // final Random rand = new Random(System.currentTimeMillis()); // 1 = backwards // 2 = random values // 3(default) = forward int rule = 3; final double r = rand.nextDouble(); if (r >= 0.8) { rule = 1;/*from w w w. jav a2 s . co m*/ } else if (r <= 0.32) { rule = 2; } else { rule = 3; } // End of the if - else // if (this.forceRequestRule != -1) { rule = this.forceRequestRule; } final List<String> ruleData = new ArrayList<String>(); if (2 == rule) { // Reversed list // for (final String term : POPULAR_TERMS) { ruleData.add(term); } // End of the for // Collections.reverse(ruleData); } else if (1 == rule) { // Random list // final Random rand2 = new Random(); for (String s : POPULAR_TERMS) { final int ni = rand2.nextInt(POPULAR_TERMS.length - 1); ruleData.add(POPULAR_TERMS[ni]); } // End of the for // } else { // Forward list // for (final String term : POPULAR_TERMS) { ruleData.add(term); } // End of the for // } // End of the if - else // return ruleData; }
From source file:org.cellprofiler.subimager.TestImageJHandlerBase.java
/** * Make an image value parameter containing a random image * /*from w w w . j a va 2s .c o m*/ * @param dim dimensions of image * @param r an instance of Random that provides the random values * @param displayName the name of the display to be created * @param fieldName the name of the parameter field to set. * @param inputMap put the image here so that it can get posted to Subimager * @return an ImageValue parameter set up for the image * * @throws IndexOutOfBoundsException */ protected Parameter makeImageValueParameter(int[] dim, Random r, String fieldName, String displayName, Map<String, NDImage> inputMap) throws IndexOutOfBoundsException { double[] buffer = new double[dim[0] * dim[1]]; for (int i = 0; i < buffer.length; i++) buffer[i] = r.nextDouble(); NDImage ndimage = new NDImage(buffer, dim); String imageID = "IMG" + UUID.randomUUID().toString(); inputMap.put(imageID, ndimage); Parameter p = new Parameter(); ImageValue iv = new ImageValue(); iv.setImageName(displayName); iv.setImageID(imageID); iv.addAxis(AxisType.X); iv.addAxis(AxisType.Y); p.setImageValue(iv); p.setName(fieldName); return p; }