List of usage examples for java.util Random nextDouble
public double nextDouble()
From source file:net.lizalab.util.RdRandRandomTest.java
/** * Runs the mean test for the specified instance of Random. * @param random The RNG instance to test. * @param doAssert Flag to indicate whether result should be asserted or simply logged. */// w ww.j a v a 2 s. c o m private void meanTest(Random random, boolean doAssert) { final String methodName = "meanTest : "; ndigits = new int[10]; // Initialize the array for (int i = 0; i < 10; i++) { ndigits[i] = 0; } double x; int n; SummaryStatistics stats = new SummaryStatistics(); long start = System.currentTimeMillis(); // Test the random number generator a whole lot for (long i = 0; i < values; i++) { // generate a new random number between 0 and 9 x = random.nextDouble() * 10.0; n = (int) x; stats.addValue(n); // count the digits in the random number ndigits[n]++; } long end = System.currentTimeMillis(); LOGGER.info("{} Time: {}ms", methodName, end - start); LOGGER.info("{} Distribution:", methodName); // Print the results for (int i = 0; i < 10; i++) { LOGGER.info("{} {}: {}", methodName, i, ndigits[i]); } double sampleMean = stats.getMean(); double sampleVar = stats.getVariance(); double meanDiff = (sampleMean - mean) / mean; LOGGER.info("{} mean: {}, diff: {}", methodName, sampleMean, meanDiff); LOGGER.info("{} sd: {}", methodName, stats.getStandardDeviation()); LOGGER.info("{} var: {}", methodName, sampleVar); // Verify results. boolean varResult = sampleVar < var; String varMsg = "Random Variance exceeds max expectation!"; boolean ci99Result = sampleMean >= smLowerRng3SD && sampleMean <= smUpperRng3SD; String ci99Msg = "Random 99.7% CI test failed!"; boolean ci95Result = sampleMean >= smLowerRng2SD && sampleMean <= smUpperRng2SD; String ci95Msg = "Random 95% CI test failed!"; if (doAssert) { assertTrue(varMsg, varResult); assertTrue(ci99Msg, ci99Result); assertTrue(ci95Msg, ci95Result); } else { if (!varResult) { LOGGER.warn("{} {}", methodName, varMsg); } if (!ci99Result) { LOGGER.warn("{} {}", methodName, ci99Msg); } if (!ci95Result) { LOGGER.warn("{} {}", methodName, ci95Msg); } } }
From source file:org.gwaspi.gui.qqPlot.java
/** * Runs the test.// w w w . j a va 2s.com */ public void run() { this.finished = false; List<XYSeries> seriesArray = new ArrayList<XYSeries>(); Random generator = new Random(); int seriesNb = -1; XYSeriesCollection dataSeries = new XYSeriesCollection(); XYSeries seriesData = new XYSeries("X"); XYSeries seriesUpper = new XYSeries("Upper bound"); XYSeries seriesLower = new XYSeries("Lower bound"); int N = 10000; List<Double> rndChiSqrDist1 = org.gwaspi.statistics.Chisquare.getChiSquareDistributionDf1(N, 1.0f); Collections.sort(rndChiSqrDist1); List<Double> rndChiSqrDist2 = org.gwaspi.statistics.Chisquare.getChiSquareDistributionDf1(N, 1.0f); Collections.sort(rndChiSqrDist2); for (int i = 0; i < rndChiSqrDist1.size(); i++) { double obsVal = rndChiSqrDist1.get(i) + (generator.nextDouble() * 0.00001); double expVal = rndChiSqrDist2.get(i); // constant chi-square boundaries // double upperVal = expVal*1.05; // double lowerVal = expVal*0.95; // double upperVal = expVal+Math.pow(Math.E,(1.96*Math.sqrt(1/expVal))); // double lowerVal = expVal-Math.pow(Math.E,(1.96*Math.sqrt(1/expVal))); double upperVal = expVal + 1.96 * Math.sqrt(0.05 * (1 - 0.05 / N)); double lowerVal = expVal - 1.96 * Math.sqrt(0.05 * (1 - 0.05 / N)); seriesData.add(obsVal, expVal); seriesLower.add(expVal, lowerVal); seriesUpper.add(expVal, upperVal); } dataSeries.addSeries(seriesData); dataSeries.addSeries(seriesLower); dataSeries.addSeries(seriesUpper); final XYDataset data = dataSeries; // create a scatter chart... final boolean withLegend = true; JFreeChart chart = ChartFactory.createScatterPlot("QQ-plot", "Obs X", "Exp X", data, PlotOrientation.VERTICAL, withLegend, false, false); final XYPlot plot = chart.getXYPlot(); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(false, true); renderer.setSeriesPaint(0, Color.blue); renderer.setSeriesPaint(1, Color.gray); renderer.setSeriesPaint(2, Color.gray); renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled(true); renderer.setSeriesShape(0, new Rectangle2D.Double(-1.0, -1.0, 2.0, 2.0)); renderer.setSeriesShape(1, new Rectangle2D.Double(-2.0, 0.0, 4.0, 0.0)); renderer.setSeriesShape(2, new Rectangle2D.Double(-2.0, 0.0, 4.0, 0.0)); plot.setRenderer(renderer); try { ChartUtilities.saveChartAsPNG(new File(System.getProperty("user.home") + "/Desktop/QQ_plot.png"), chart, 400, 400); } catch (IOException ex) { log.error("Problem occurred creating chart", ex); } }
From source file:org.apache.hadoop.hive.serde2.binarysortable.MyTestClass.java
public int randomFill(Random r, ExtraTypeInfo extraTypeInfo) { int randField = r.nextInt(MyTestClass.fieldCount); int field = 0; myBool = (randField == field++) ? null : (r.nextInt(1) == 1); myByte = (randField == field++) ? null : Byte.valueOf((byte) r.nextInt()); myShort = (randField == field++) ? null : Short.valueOf((short) r.nextInt()); myInt = (randField == field++) ? null : Integer.valueOf(r.nextInt()); myLong = (randField == field++) ? null : Long.valueOf(r.nextLong()); myFloat = (randField == field++) ? null : Float.valueOf(r.nextFloat() * 10 - 5); myDouble = (randField == field++) ? null : Double.valueOf(r.nextDouble() * 10 - 5); myString = (randField == field++) ? null : MyTestPrimitiveClass.getRandString(r); myHiveChar = (randField == field++) ? null : MyTestPrimitiveClass.getRandHiveChar(r, extraTypeInfo); myHiveVarchar = (randField == field++) ? null : MyTestPrimitiveClass.getRandHiveVarchar(r, extraTypeInfo); myBinary = MyTestPrimitiveClass.getRandBinary(r, r.nextInt(1000)); myDecimal = (randField == field++) ? null : MyTestPrimitiveClass.getRandHiveDecimal(r, extraTypeInfo); myDate = (randField == field++) ? null : MyTestPrimitiveClass.getRandDate(r); myTimestamp = (randField == field++) ? null : RandomTypeUtil.getRandTimestamp(r); myIntervalYearMonth = (randField == field++) ? null : MyTestPrimitiveClass.getRandIntervalYearMonth(r); myIntervalDayTime = (randField == field++) ? null : MyTestPrimitiveClass.getRandIntervalDayTime(r); myStruct = (randField == field++) ? null : new MyTestInnerStruct(r.nextInt(5) - 2, r.nextInt(5) - 2); myList = (randField == field++) ? null : getRandIntegerArray(r); return field; }
From source file:dremel.common.AvroTest.java
@SuppressWarnings(value = "unchecked") private static Object generateRandomDataRecursive(Schema schema, Random random, int size) { switch (schema.getType()) { case RECORD://from w w w . ja v a 2 s . c o m GenericRecord record = new GenericData.Record(schema); boolean isFieldsEmpty = true; for (Schema.Field field : schema.getFields()) { Object o = generateRandomDataRecursive(field.schema(), random, size); if (o != null) { record.put(field.name(), o); isFieldsEmpty = isFieldsEmpty && o instanceof GenericArray && ((GenericArray<Object>) o).size() == 0; } } return isFieldsEmpty ? null : record; case ARRAY: int length = size + (random.nextInt(10)); GenericArray<Object> array = new GenericData.Array<Object>(length <= 0 ? 0 : length, schema); Object o; for (int i = 0; i < length; i++) { o = generateRandomDataRecursive(schema.getElementType(), random, size > 0 ? size - 1 : 0); if (o != null) array.add(o); } return array; case STRING: return generateRandomUtf8(random, 40); case INT: return random.nextInt(); case LONG: return random.nextLong(); case FLOAT: return random.nextFloat(); case DOUBLE: return random.nextDouble(); case BOOLEAN: return random.nextBoolean(); default: throw new RuntimeException("Unknown type: " + schema); } }
From source file:com.cburch.draw.shapes.Poly.java
private Location getRandomBoundaryPoint(Bounds bds, Random rand) { Handle[] hs = handles;//from w w w . jav a2 s.c o m double[] ls = lens; if (ls == null) { ls = new double[hs.length + (closed ? 1 : 0)]; double total = 0.0; for (int i = 0; i < ls.length; i++) { int j = (i + 1) % hs.length; total += LineUtil.distance(hs[i].getX(), hs[i].getY(), hs[j].getX(), hs[j].getY()); ls[i] = total; } lens = ls; } double pos = ls[ls.length - 1] * rand.nextDouble(); for (int i = 0; true; i++) { if (pos < ls[i]) { Handle p = hs[i]; Handle q = hs[(i + 1) % hs.length]; double u = Math.random(); int x = (int) Math.round(p.getX() + u * (q.getX() - p.getX())); int y = (int) Math.round(p.getY() + u * (q.getY() - p.getY())); return Location.create(x, y); } } }
From source file:MetaFramework.Bayesian.java
/** * Draws a number from poisson distribution * * @param l//w ww . j a v a 2 s.c om * @return */ public int poisson(double l) { Random random = new Random(); double limit = Math.exp(-l); double prod = random.nextDouble(); int n = 0; for (n = 0; prod >= limit; n++) prod *= random.nextDouble(); return n; }
From source file:com.adflake.AdFlakeManager.java
public Ration getNextDartedVideoRation(List<Ration> usedVideoRations) { Random random = new Random(); double actualWeight = 0; for (Ration ration : _videoRationsList) { if (usedVideoRations.contains(ration)) continue; actualWeight += ration.weight;//from ww w .j a va 2 s . c om } double r = random.nextDouble() * actualWeight; double s = 0; Log.d(AdFlakeUtil.ADFLAKE, "Dart is <" + r + "> of <" + actualWeight + "> and total <" + _totalWeight + ">"); Iterator<Ration> it = this._videoRationsList.iterator(); Ration ration = null; while (it.hasNext()) { ration = it.next(); if (usedVideoRations.contains(ration)) continue; s += ration.weight; if (s >= r) { break; } } return ration; }
From source file:org.apache.hadoop.hbase.client.TestBatchedUpload.java
/** * Write data to the htable. While randomly killing/shutting down regionservers. * @param table/*from www .java 2s .c om*/ * @param numRows * @param action -- enum RegionServerAction which defines the type of action. * @return number of attempts to complete the batch. * @throws IOException * @throws InterruptedException */ public int writeData(HTable table, long numRows, RegionServerAction action) throws IOException, InterruptedException { int attempts = 0; int MAX = 10; MiniHBaseCluster cluster = TEST_UTIL.getMiniHBaseCluster(); Random rand = new Random(5234234); double killProb = 2.0 / numRows; double prob; int kills = 0; while (attempts < MAX) { try { attempts++; // start batched session table.startBatchedLoad(); // do batched puts // with WAL turned off for (long i = 0; i < numRows; i++) { byte[] rowKey = longToByteArrayKey(i); Put put = new Put(rowKey); byte[] value = rowKey; // value is the same as the row key put.add(FAMILY, QUALIFIER, value); put.setWriteToWAL(false); prob = rand.nextDouble(); if (kills < 2 && prob < killProb) { // kill up to 2 rs kills++; // Find the region server for the next put HRegionLocation regLoc = table.getRegionLocation(put.row); int srcRSIdx = cluster.getServerWith(regLoc.getRegionInfo().getRegionName()); LOG.debug("Try " + attempts + " written Puts : " + i); if (action == RegionServerAction.KILL_REGIONSERVER) { // abort the region server LOG.info("Killing region server " + srcRSIdx + " before the next put. Got probability " + prob + " < " + killProb); cluster.abortRegionServer(srcRSIdx); } else if (action == RegionServerAction.MOVE_REGION) { // move the region to some other Region Server HRegionServer dstRS = cluster .getRegionServer((srcRSIdx + 1) % cluster.getLiveRegionServerThreads().size()); LOG.info("Moving region " + regLoc.getRegionInfo().getRegionName() + "from " + cluster.getRegionServer(srcRSIdx) + " to " + dstRS); moveRegionAndWait(cluster.getRegionServer(srcRSIdx) .getOnlineRegion(regLoc.getRegionInfo().getRegionName()), dstRS); } // keep decreasing the probability of killing the RS killProb = killProb / 2; } table.put(put); } LOG.info("Written all puts. Trying to end Batch"); // complete batched puts table.endBatchedLoad(); return attempts; } catch (IOException e) { e.printStackTrace(); LOG.info("Failed try # " + attempts); } } throw new IOException("Failed to do batched puts after " + MAX + " retries."); }
From source file:hivemall.anomaly.ChangeFinder2DTest.java
@Test public void testPoissonDist() throws HiveException { final int examples = 10000; final int dims = 3; final PoissonDistribution[] poisson = new PoissonDistribution[] { new PoissonDistribution(10.d), new PoissonDistribution(5.d), new PoissonDistribution(20.d) }; final Random rand = new Random(42); final Double[] x = new Double[dims]; final List<Double> xList = Arrays.asList(x); Parameters params = new Parameters(); params.set(LossFunction.logloss);//from ww w.j a v a 2s . c o m params.r1 = 0.01d; params.k = 6; params.T1 = 10; params.T2 = 5; PrimitiveObjectInspector oi = PrimitiveObjectInspectorFactory.javaDoubleObjectInspector; ListObjectInspector listOI = ObjectInspectorFactory.getStandardListObjectInspector(oi); final ChangeFinder2D cf = new ChangeFinder2D(params, listOI); final double[] outScores = new double[2]; println("# time x0 x1 x2 outlier change"); for (int i = 0; i < examples; i++) { double r = rand.nextDouble(); x[0] = r * poisson[0].sample(); x[1] = r * poisson[1].sample(); x[2] = r * poisson[2].sample(); cf.update(xList, outScores); printf("%d %f %f %f %f %f%n", i, x[0], x[1], x[2], outScores[0], outScores[1]); } }