Java Code Examples for java.util.Random#nextDouble()

The following examples show how to use java.util.Random#nextDouble() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestNearestNeighbourFS.java    From phtree with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryND64Random10() {
	//final int DIM = 4;//5
	//final int LOOP = 1;//10;
	final int N = 1000;
	final int NQ = 100;
	final int MAXV = 1;
	for (int d = 2; d < 10; d++) {
		int DIM = d;
		final Random R = new Random(d);
		PhTreeSolidF<Object> ind = newTreeSF(DIM);
		PhKnnQuerySF<Object> q = ind.nearestNeighbour(10, newDistFn(ind), new double[DIM]);
		populate(ind, R, N, DIM, MAXV);
		for (int i = 0; i < NQ; i++) {
			double[] v = new double[DIM];
			for (int j = 0; j < DIM; j++) {
				v[j] = R.nextDouble()*MAXV;
			}
			ArrayList<PhEntrySF<Object>> exp = nearestNeighborK(ind, 10, v);
			List<PhEntrySF<Object>> nnList = toList(q.reset(10, null, v));
			
			assertTrue("i=" + i + " d=" + d, !nnList.isEmpty());
			check(v, exp, nnList);
		}
	}
}
 
Example 2
Source File: DoubleComparatorTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
protected Double[] getSortedTestData() {
	Random rnd = new Random(874597969123412338L);
	double rndDouble = rnd.nextDouble();
	if (rndDouble < 0) {
		rndDouble = -rndDouble;
	}
	if (rndDouble == Double.MAX_VALUE) {
		rndDouble -= 3;
	}
	if (rndDouble <= 2) {
		rndDouble += 3;
	}
	return new Double[]{
		Double.valueOf(-rndDouble),
		Double.valueOf(-1.0D),
		Double.valueOf(0.0D),
		Double.valueOf(2.0D),
		Double.valueOf(rndDouble),
		Double.valueOf(Double.MAX_VALUE)};
}
 
Example 3
Source File: LegendreGaussIntegratorTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testExactIntegration()
    throws ConvergenceException, FunctionEvaluationException {
    Random random = new Random(86343623467878363l);
    for (int n = 2; n < 6; ++n) {
        LegendreGaussIntegrator integrator =
            new LegendreGaussIntegrator(n, 64);

        // an n points Gauss-Legendre integrator integrates 2n-1 degree polynoms exactly
        for (int degree = 0; degree <= 2 * n - 1; ++degree) {
            for (int i = 0; i < 10; ++i) {
                double[] coeff = new double[degree + 1];
                for (int k = 0; k < coeff.length; ++k) {
                    coeff[k] = 2 * random.nextDouble() - 1;
                }
                PolynomialFunction p = new PolynomialFunction(coeff);
                double result    = integrator.integrate(p, -5.0, 15.0);
                double reference = exactIntegration(p, -5.0, 15.0);
                assertEquals(n + " " + degree + " " + i, reference, result, 1.0e-12 * (1.0 + Math.abs(reference)));
            }
        }

    }
}
 
Example 4
Source File: SchurTransformerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testRandomDataNormalDistribution() {
    for (int run = 0; run < 100; run++) {
        Random r = new Random(System.currentTimeMillis());
        NormalDistribution dist = new NormalDistribution(0.0, r.nextDouble() * 5);

        // matrix size
        int size = r.nextInt(20) + 4;

        double[][] data = new double[size][size];
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                data[i][j] = dist.sample();
            }
        }

        RealMatrix m = MatrixUtils.createRealMatrix(data);
        RealMatrix s = checkAEqualPTPt(m);
        checkSchurForm(s);
    }
}
 
Example 5
Source File: GrowthDataErrorsEditor.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Create a duplicate height observation in the encounter that is off slightly.
 * @param encounter The encounter that contains the observation
 */
public static void introduceHeightDuplicateError(HealthRecord.Encounter encounter,
                                                 Random random) {
  HealthRecord.Observation htObs = heightObservation(encounter);
  double heightValue = (Double) htObs.value;
  double jitter = random.nextDouble() - 0.5;
  HealthRecord.Observation newObs = encounter.addObservation(htObs.start, htObs.type,
      heightValue + jitter, "Body Height");
  newObs.category = "vital-signs";
  newObs.unit = "cm";
}
 
Example 6
Source File: ArrayRealVectorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testCombineToSelfMixedTypes() {
    final Random random = new Random(20110726);
    final int dim = 10;
    final double a = (2 * random.nextDouble() - 1);
    final double b = (2 * random.nextDouble() - 1);
    final RealVector x = new ArrayRealVector(dim);
    final RealVector y = new OpenMapRealVector(dim, 0d);
    final double[] expected = new double[dim];
    for (int i = 0; i < dim; i++) {
        final double xi = 2 * random.nextDouble() - 1;
        final double yi = 2 * random.nextDouble() - 1;
        x.setEntry(i, xi);
        y.setEntry(i, yi);
        expected[i] = a * xi + b * yi;
    }
    Assert.assertSame(x, x.combineToSelf(a, b, y));
    final double[] actual = x.getData();
    for (int i = 0; i < dim; i++) {
        final double delta;
        if (expected[i] == 0d) {
            delta = Math.ulp(1d);
        } else {
            delta = Math.ulp(expected[i]);
        }
        Assert.assertEquals("elements [" + i + "] differ",
                            expected[i],
                            actual[i],
                            delta);
    }
}
 
Example 7
Source File: PerformanceTest.java    From pumpernickel with MIT License 5 votes vote down vote up
public void testAdditions(int iterations, int additions) {
	Random random = new Random(0);
	long[] times = new long[iterations];
	for (int a = 0; a < iterations; a++) {
		random.setSeed(0);
		AreaX sum = new AreaX();
		times[a] = System.currentTimeMillis();
		for (int b = 0; b < additions; b++) {
			if (cancelled)
				return;
			float percent = ((float) a) / ((float) iterations);
			percent = percent + 1f / (iterations) * (b) / (additions);
			progress.setValue((int) (percent * (progress.getMaximum() - progress
					.getMinimum())) + progress.getMinimum());

			double x = 1000 * random.nextDouble();
			double y = 1000 * random.nextDouble();
			Shape shape;
			if (type.getSelectedIndex() == 0) {
				shape = createDiamond((float) x, (float) y);
			} else if (type.getSelectedIndex() == 1) {
				shape = createQuad((float) x, (float) y);
			} else { // use cubics
				shape = new Ellipse2D.Double(x, y, 30, 30);
			}
			AreaX k = new AreaX(shape);
			sum.add(k);
		}
		times[a] = System.currentTimeMillis() - times[a];
	}
	Arrays.sort(times);
	printStream.println("Median Time: " + times[times.length / 2] + " ms");
}
 
Example 8
Source File: SVDPlusPlus.java    From cf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Model constructor
 *
 * @param datamodel DataModel instance
 * @param numFactors Number of latent factors
 * @param numIters Number of iterations
 * @param gamma Learning rate hyper-parameter
 * @param lambda Regularization hyper-parameter
 * @param seed Seed for random numbers generation
 */
public SVDPlusPlus(
    DataModel datamodel, int numFactors, int numIters, double gamma, double lambda, long seed) {
  super(datamodel);

  this.numFactors = numFactors;
  this.numIters = numIters;
  this.gamma = gamma;
  this.lambda = lambda;

  int numUsers = datamodel.getNumberOfUsers();
  int numItems = datamodel.getNumberOfItems();

  Random generator = new Random(seed);

  this.bu = new double[numUsers];
  this.p = new double[numUsers][numFactors];
  for (int u = 0; u < numUsers; u++) {
    this.bu[u] = generator.nextDouble();
    for (int k = 0; k < numFactors; k++) {
      this.p[u][k] = generator.nextDouble();
    }
  }

  this.bi = new double[numItems];
  this.q = new double[numItems][numFactors];
  this.y = new double[numItems][numFactors];
  for (int i = 0; i < numItems; i++) {
    this.bi[i] = generator.nextDouble();
    for (int k = 0; k < numFactors; k++) {
      this.q[i][k] = generator.nextDouble();
      this.y[i][k] = generator.nextDouble();
    }
  }
}
 
Example 9
Source File: HermiteInterpolatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private PolynomialFunction randomPolynomial(int degree, Random random) {
    double[] coeff = new double[ 1 + degree];
    for (int j = 0; j < degree; ++j) {
        coeff[j] = random.nextDouble();
    }
    return new PolynomialFunction(coeff);
}
 
Example 10
Source File: BlockPitKiln.java    From TFC2 with GNU General Public License v3.0 5 votes vote down vote up
/*******************************************************************************
 * 2. Rendering
 *******************************************************************************/

@Override
@SideOnly(Side.CLIENT)
public void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand)
{
	TilePitKiln te = (TilePitKiln)world.getTileEntity(pos);
	if(te.recentCraftResult.result == ProcessEnum.WORKING)
	{
		double x = 0;
		double z = 0;
		double y = 1;

		if(!world.isAirBlock(pos.up()))
			y = 2;
		if(!world.isAirBlock(pos.up(2)))
			y = 3;

		if(y < 3)
		{
			x = rand.nextDouble() * 0.7;
			z = rand.nextDouble() * 0.7;
			world.spawnParticle(EnumParticleTypes.FLAME, pos.getX()+0.15+x, pos.getY()+y, pos.getZ()+0.15+z, 0, 0.02, 0);
			x = rand.nextDouble() * 0.7;
			z = rand.nextDouble() * 0.7;
			world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, pos.getX()+0.15+x, pos.getY()+y, pos.getZ()+0.15+z, 0, 0.02, 0);
		}
		x = rand.nextDouble() * 0.7;
		z = rand.nextDouble() * 0.7;
		world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, pos.getX()+0.15+x, pos.getY()+y, pos.getZ()+0.15+z, 0, 0.02, 0);
	}
}
 
Example 11
Source File: RandomText.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Item randomItem(Random random, List<Item> items, double ratioSum) {
    assert (items.size() > 0); // Prevent infinite loop
    while (true) { // A cycle should prevent rounding errors problems
        double r = random.nextDouble() * ratioSum;
        for (Item item : items) {
            r -= item.ratio;
            if (r <= 0) {
                return item;
            }
        }
    }
}
 
Example 12
Source File: AbstractRealVectorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testCombineToSelf() {
    final Random random = new Random(20110726);
    final int dim = 10;
    final double a = (2 * random.nextDouble() - 1);
    final double b = (2 * random.nextDouble() - 1);
    final RealVector x = new TestVectorImpl(new double[dim]);
    final RealVector y = new TestVectorImpl(new double[dim]);
    final double[] expected = new double[dim];
    for (int i = 0; i < dim; i++) {
        final double xi = 2 * random.nextDouble() - 1;
        final double yi = 2 * random.nextDouble() - 1;
        x.setEntry(i, xi);
        y.setEntry(i, yi);
        expected[i] = a * xi + b * yi;
    }
    Assert.assertSame(x, x.combineToSelf(a, b, y));
    final double[] actual = x.getData();
    for (int i = 0; i < dim; i++) {
        final double delta;
        if (expected[i] == 0d) {
            delta = Math.ulp(1d);
        } else {
            delta = Math.ulp(expected[i]);
        }
        Assert.assertEquals("elements [" + i + "] differ", expected[i],
                            actual[i], delta);
    }
}
 
Example 13
Source File: InstantSerializerTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
private static int rndNanos(Random rnd) {
	return (int) (rnd.nextDouble() * 999999999);
}
 
Example 14
Source File: GillStepInterpolatorTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void serialization()
  throws DerivativeException, IntegratorException,
         IOException, ClassNotFoundException {

  TestProblem3 pb = new TestProblem3(0.9);
  double step = (pb.getFinalTime() - pb.getInitialTime()) * 0.0003;
  GillIntegrator integ = new GillIntegrator(step);
  integ.addStepHandler(new ContinuousOutputModel());
  integ.integrate(pb,
                  pb.getInitialTime(), pb.getInitialState(),
                  pb.getFinalTime(), new double[pb.getDimension()]);

  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  ObjectOutputStream    oos = new ObjectOutputStream(bos);
  for (StepHandler handler : integ.getStepHandlers()) {
      oos.writeObject(handler);
  }

  assertTrue(bos.size () > 700000);
  assertTrue(bos.size () < 701000);

  ByteArrayInputStream  bis = new ByteArrayInputStream(bos.toByteArray());
  ObjectInputStream     ois = new ObjectInputStream(bis);
  ContinuousOutputModel cm  = (ContinuousOutputModel) ois.readObject();

  Random random = new Random(347588535632l);
  double maxError = 0.0;
  for (int i = 0; i < 1000; ++i) {
    double r = random.nextDouble();
    double time = r * pb.getInitialTime() + (1.0 - r) * pb.getFinalTime();
    cm.setInterpolatedTime(time);
    double[] interpolatedY = cm.getInterpolatedState ();
    double[] theoreticalY  = pb.computeTheoreticalState(time);
    double dx = interpolatedY[0] - theoreticalY[0];
    double dy = interpolatedY[1] - theoreticalY[1];
    double error = dx * dx + dy * dy;
    if (error > maxError) {
      maxError = error;
    }
  }

  assertTrue(maxError < 0.003);

}
 
Example 15
Source File: TestGeoUtils.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
static double randomInRange(Random random, double min, double max) {
  return min + (max - min) * random.nextDouble();
}
 
Example 16
Source File: EigenDecompositionImplTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public static RealMatrix createOrthogonalMatrix(final Random r, final int size) {

        final double[][] data = new double[size][size];

        for (int i = 0; i < size; ++i) {
            final double[] dataI = data[i];
            double norm2 = 0;
            do {

                // generate randomly row I
                for (int j = 0; j < size; ++j) {
                    dataI[j] = 2 * r.nextDouble() - 1;
                }

                // project the row in the subspace orthogonal to previous rows
                for (int k = 0; k < i; ++k) {
                    final double[] dataK = data[k];
                    double dotProduct = 0;
                    for (int j = 0; j < size; ++j) {
                        dotProduct += dataI[j] * dataK[j];
                    }
                    for (int j = 0; j < size; ++j) {
                        dataI[j] -= dotProduct * dataK[j];
                    }
                }

                // normalize the row
                norm2 = 0;
                for (final double dataIJ : dataI) {
                    norm2 += dataIJ * dataIJ;
                }
                final double inv = 1.0 / Math.sqrt(norm2);
                for (int j = 0; j < size; ++j) {
                    dataI[j] *= inv;
                }

            } while (norm2 * size < 0.01);
        }

        return MatrixUtils.createRealMatrix(data);

    }
 
Example 17
Source File: RoundRectangle.java    From Logisim with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected Location getRandomPoint(Bounds bds, Random rand) {
	if (getPaintType() == DrawAttr.PAINT_STROKE) {
		int w = getWidth();
		int h = getHeight();
		int r = radius;
		int horz = Math.max(0, w - 2 * r); // length of horizontal segment
		int vert = Math.max(0, h - 2 * r);
		double len = 2 * horz + 2 * vert + 2 * Math.PI * r;
		double u = len * rand.nextDouble();
		int x = getX();
		int y = getY();
		if (u < horz) {
			x += r + (int) u;
		} else if (u < 2 * horz) {
			x += r + (int) (u - horz);
			y += h;
		} else if (u < 2 * horz + vert) {
			y += r + (int) (u - 2 * horz);
		} else if (u < 2 * horz + 2 * vert) {
			x += w;
			y += (u - 2 * w - h);
		} else {
			int rx = radius;
			int ry = radius;
			if (2 * rx > w)
				rx = w / 2;
			if (2 * ry > h)
				ry = h / 2;
			u = 2 * Math.PI * rand.nextDouble();
			int dx = (int) Math.round(rx * Math.cos(u));
			int dy = (int) Math.round(ry * Math.sin(u));
			if (dx < 0) {
				x += r + dx;
			} else {
				x += r + horz + dx;
			}
			if (dy < 0) {
				y += r + dy;
			} else {
				y += r + vert + dy;
			}
		}

		int d = getStrokeWidth();
		if (d > 1) {
			x += rand.nextInt(d) - d / 2;
			y += rand.nextInt(d) - d / 2;
		}
		return Location.create(x, y);
	} else {
		return super.getRandomPoint(bds, rand);
	}
}
 
Example 18
Source File: EigenDecompositionTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public static RealMatrix createOrthogonalMatrix(final Random r, final int size) {

        final double[][] data = new double[size][size];

        for (int i = 0; i < size; ++i) {
            final double[] dataI = data[i];
            double norm2 = 0;
            do {

                // generate randomly row I
                for (int j = 0; j < size; ++j) {
                    dataI[j] = 2 * r.nextDouble() - 1;
                }

                // project the row in the subspace orthogonal to previous rows
                for (int k = 0; k < i; ++k) {
                    final double[] dataK = data[k];
                    double dotProduct = 0;
                    for (int j = 0; j < size; ++j) {
                        dotProduct += dataI[j] * dataK[j];
                    }
                    for (int j = 0; j < size; ++j) {
                        dataI[j] -= dotProduct * dataK[j];
                    }
                }

                // normalize the row
                norm2 = 0;
                for (final double dataIJ : dataI) {
                    norm2 += dataIJ * dataIJ;
                }
                final double inv = 1.0 / FastMath.sqrt(norm2);
                for (int j = 0; j < size; ++j) {
                    dataI[j] *= inv;
                }

            } while (norm2 * size < 0.01);
        }

        return MatrixUtils.createRealMatrix(data);

    }
 
Example 19
Source File: TestEventReceiver.java    From database with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Pumps a bunch of events through and then verifies that the start events
 * are correlated with the end events and that the size of the
 * {@link LinkedHashMap} is bounded by the #of incomplete events no older
 * than the configured eventHistoryMillis.
 * 
 * @throws InterruptedException
 */
public void test_purgesHistory() throws InterruptedException {

    final long eventHistoryMillis = 1000L;
    
    final EventBTree eventBTree = EventBTree.createTransient();

    final EventReceiver eventReceiver = new EventReceiver(
            eventHistoryMillis, eventBTree);

    final IBigdataFederation fed = new MockFederation(eventReceiver);

    final Random r = new Random();
    
    final long begin = System.currentTimeMillis();
    long elapsed;
    int nevents = 0;
    while ((elapsed = System.currentTimeMillis() - begin) < eventHistoryMillis / 2) {
        
        final Event e = new MyEvent(fed, new EventResource("testIndex"),
                "testEventType");

        if (r.nextDouble() < .2) {

            // instantaneous event.
            e.end();

        } else {

            /*
             * event with duration.
             */
            e.start();

            try {

                Thread
                        .sleep(r.nextInt((int) eventHistoryMillis / 10)/* ms */);

            } finally {

                e.end();

            }

        }

        nevents++;

    }

    // all the events should be in the cache.
    assertEquals(nevents, eventReceiver.eventCache.size());
    
    // sleep until the events should be expired.
    Thread.sleep(eventHistoryMillis);
    
    // prune the event cache using the specified timestamp.
    eventReceiver.pruneHistory(System.currentTimeMillis());

    // should be empty.
    assertEquals(0, eventReceiver.eventCache.size());
    
}
 
Example 20
Source File: ProbTool.java    From iotdb-benchmark with Apache License 2.0 2 votes vote down vote up
/**
 * 使用QUERY_SEED参数作为随机数种子
 *
 * @param p 返回true的概率
 * @return 布尔值
 */
public boolean returnTrueByProb(double p, Random random) {
    return random.nextDouble() < p;
}