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

The following examples show how to use java.util.Random#nextGaussian() . 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: StlTestDataGenerator.java    From stl-decomp-4j with Apache License 2.0 6 votes vote down vote up
double[] createNoisySeasonalData(int length, int period, double seasonalAmplitude, double trendSlope,
		double noiseSigma, long seed) {

	this.seed = seed;
	Random rand = new Random(seed);

	double[] y = new double[length];
	double dx = 2 * Math.PI / period;
	for (int i = 0; i < length; ++i) {
		double x = i * dx;
		double e = noiseSigma * rand.nextGaussian();
		y[i] = trendSlope * x + seasonalAmplitude * Math.sin(x) + e;
	}

	return y;
}
 
Example 2
Source File: PercentileAggregatorTest.java    From kylin with Apache License 2.0 6 votes vote down vote up
private PercentileAggregator createPercentileAggreator(int sumNums, Integer sqrtNum, Integer compression) {
    compression = compression == null ? DEFAULT_COMPRESSION : compression;
    PercentileAggregator aggregator = new PercentileAggregator(compression);
    Random random = new Random();

    for (int i = 0; i < sumNums; i++) {
        double d = 0;
        if (sqrtNum == null)
            d = random.nextInt(1000000000);
        else
            d = Math.sqrt(sqrtNum.intValue()) * random.nextGaussian();

        PercentileCounter c = new PercentileCounter(compression, 0.5);
        c.add(d);
        aggregator.aggregate(c);
    }
    return aggregator;
}
 
Example 3
Source File: SwingChartGestureDemo.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a dataset, consisting of two series of monthly data.
 *
 * @return the dataset.
 */
private static XYDataset createDataset() {
  XYSeriesCollection data = new XYSeriesCollection();

  Random r = new Random(System.currentTimeMillis());

  for (int i = 0; i < 3; i++) {
    XYSeries s = new XYSeries("Series" + i);
    for (int x = 0; x < 100; x++) {
      double v = r.nextGaussian() * (i + 1);
      s.add(x, v);
    }
    data.addSeries(s);
  }
  return data;
}
 
Example 4
Source File: PolynomialFitterTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private PolynomialFunction buildRandomPolynomial(int degree, Random randomizer) {
    final double[] coefficients = new double[degree + 1];
    for (int i = 0; i <= degree; ++i) {
        coefficients[i] = randomizer.nextGaussian();
    }
    return new PolynomialFunction(coefficients);
}
 
Example 5
Source File: MixServerTest.java    From incubator-hivemall with Apache License 2.0 5 votes vote down vote up
@Test
public void testSSL() throws InterruptedException {
    int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
        new String[] {"-port", Integer.toString(port), "-sync_threshold", "3", "-ssl"},
        MixServer.getOptions());
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);

    waitForState(server, ServerState.RUNNING);

    PredictionModel model = new NewDenseModel(16777216);
    model.configureClock();
    MixClient client = null;
    try {
        client = new MixClient(MixEventName.average, "testSSL", "localhost:" + port, true, 2,
            model);
        model.configureMix(client, false);

        final Random rand = new Random(43);
        for (int i = 0; i < 100000; i++) {
            Integer feature = Integer.valueOf(rand.nextInt(100));
            float weight = (float) rand.nextGaussian();
            model.set(feature, new WeightValue(weight));
        }

        Thread.sleep(5000L);

        long numMixed = model.getNumMixed();
        Assert.assertEquals("number of mix events: " + numMixed, numMixed, 0L);

        serverExec.shutdown();
    } finally {
        IOUtils.closeQuietly(client);
    }
}
 
Example 6
Source File: ProfileParallelHistogram1D.java    From diirt with MIT License 5 votes vote down vote up
/**
 * Creates Gaussian random histogram data of the appropriate size.
 * Updates the circular point data buffer with the histogram data.
 */
private void initDatasets(){
    //Creates data
    Random rand = new Random(1);
    double[] data = new double[nSamples];
    for (int i = 0; i < nSamples; i++) {
        data[i] = rand.nextGaussian();
    }

    dataset = Cell1DDatasets.datasetFrom(new ArrayDouble(data), ListNumbers.linearList(0, 1, nSamples));
}
 
Example 7
Source File: RandomTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Repeated calls to nextGaussian produce at least two distinct results
 */
public void testNextGaussian() {
    Random r = new Random();
    double f = r.nextGaussian();
    int i = 0;
    while (i < NCALLS && r.nextGaussian() == f)
        ++i;
    assertTrue(i < NCALLS);
}
 
Example 8
Source File: CosineHash.java    From TarsosLSH with GNU Lesser General Public License v3.0 5 votes vote down vote up
public CosineHash(int dimensions){
	Random rand  = new Random();
	randomProjection = new Vector(dimensions);
	for(int d=0; d<dimensions; d++) {
		//mean 0
		//standard deviation 1.0
		double val = rand.nextGaussian();
		randomProjection.set(d, val);
	}
}
 
Example 9
Source File: SensorSource.java    From examples-java with Apache License 2.0 5 votes vote down vote up
/** run() continuously emits SensorReadings by emitting them through the SourceContext. */
@Override
public void run(SourceContext<SensorReading> srcCtx) throws Exception {

    // initialize random number generator
    Random rand = new Random();
    // look up index of this parallel task
    int taskIdx = this.getRuntimeContext().getIndexOfThisSubtask();

    // initialize sensor ids and temperatures
    String[] sensorIds = new String[10];
    double[] curFTemp = new double[10];
    for (int i = 0; i < 10; i++) {
        sensorIds[i] = "sensor_" + (taskIdx * 10 + i);
        curFTemp[i] = 65 + (rand.nextGaussian() * 20);
    }

    while (running) {

        // get current time
        long curTime = Calendar.getInstance().getTimeInMillis();

        // emit SensorReadings
        for (int i = 0; i < 10; i++) {
            // update current temperature
            curFTemp[i] += rand.nextGaussian() * 0.5;
            // emit reading
            srcCtx.collect(new SensorReading(sensorIds[i], curTime, curFTemp[i]));
        }

        // wait for 100 ms
        Thread.sleep(100);
    }
}
 
Example 10
Source File: RandomTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Repeated calls to nextGaussian produce at least two distinct results
 */
public void testNextGaussian() {
    Random r = new Random();
    double f = r.nextGaussian();
    int i = 0;
    while (i < NCALLS && r.nextGaussian() == f)
        ++i;
    assertTrue(i < NCALLS);
}
 
Example 11
Source File: PolynomialCurveFitterTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private PolynomialFunction buildRandomPolynomial(int degree, Random randomizer) {
    final double[] coefficients = new double[degree + 1];
    for (int i = 0; i <= degree; ++i) {
        coefficients[i] = randomizer.nextGaussian();
    }
    return new PolynomialFunction(coefficients);
}
 
Example 12
Source File: RandomTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Repeated calls to nextGaussian produce at least two distinct results
 */
public void testNextGaussian() {
    Random r = new Random();
    double f = r.nextGaussian();
    int i = 0;
    while (i < NCALLS && r.nextGaussian() == f)
        ++i;
    assertTrue(i < NCALLS);
}
 
Example 13
Source File: MatrixUtils.java    From meka with GNU General Public License v3.0 5 votes vote down vote up
/** A 2D array of Gaussian random numbers */
public static double[][] randn(int rows, int cols, Random r) {
	double X[][] = new double[rows][cols];
	for(int i = 0; i < rows; i++) {
		for(int j = 0; j < cols; j++) {
			X[i][j] = r.nextGaussian();
		}
	}
	return X;
}
 
Example 14
Source File: HarmonicFitterTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testUnsorted() throws OptimizationException {
    Random randomizer = new Random(64925784252l);
    HarmonicFunction f = new HarmonicFunction(0.2, 3.4, 4.1);

    HarmonicFitter fitter =
        new HarmonicFitter(new LevenbergMarquardtOptimizer());

    // build a regularly spaced array of measurements
    int size = 100;
    double[] xTab = new double[size];
    double[] yTab = new double[size];
    for (int i = 0; i < size; ++i) {
        xTab[i] = 0.1 * i;
        yTab[i] = f.value(xTab[i]) + 0.01 * randomizer.nextGaussian();
    }

    // shake it
    for (int i = 0; i < size; ++i) {
        int i1 = randomizer.nextInt(size);
        int i2 = randomizer.nextInt(size);
        double xTmp = xTab[i1];
        double yTmp = yTab[i1];
        xTab[i1] = xTab[i2];
        yTab[i1] = yTab[i2];
        xTab[i2] = xTmp;
        yTab[i2] = yTmp;
    }

    // pass it to the fitter
    for (int i = 0; i < size; ++i) {
        fitter.addObservedPoint(1.0, xTab[i], yTab[i]);
    }

    HarmonicFunction fitted = fitter.fit();
    assertEquals(f.getAmplitude(), fitted.getAmplitude(), 7.6e-4);
    assertEquals(f.getPulsation(), fitted.getPulsation(), 3.5e-3);
    assertEquals(f.getPhase(),     MathUtils.normalizeAngle(fitted.getPhase(), f.getPhase()), 1.5e-2);

}
 
Example 15
Source File: HarmonicFitterTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testUnsorted() {
    Random randomizer = new Random(64925784252l);
    final double a = 0.2;
    final double w = 3.4;
    final double p = 4.1;
    HarmonicOscillator f = new HarmonicOscillator(a, w, p);

    HarmonicFitter fitter =
        new HarmonicFitter(new LevenbergMarquardtOptimizer());

    // build a regularly spaced array of measurements
    int size = 100;
    double[] xTab = new double[size];
    double[] yTab = new double[size];
    for (int i = 0; i < size; ++i) {
        xTab[i] = 0.1 * i;
        yTab[i] = f.value(xTab[i]) + 0.01 * randomizer.nextGaussian();
    }

    // shake it
    for (int i = 0; i < size; ++i) {
        int i1 = randomizer.nextInt(size);
        int i2 = randomizer.nextInt(size);
        double xTmp = xTab[i1];
        double yTmp = yTab[i1];
        xTab[i1] = xTab[i2];
        yTab[i1] = yTab[i2];
        xTab[i2] = xTmp;
        yTab[i2] = yTmp;
    }

    // pass it to the fitter
    for (int i = 0; i < size; ++i) {
        fitter.addObservedPoint(1, xTab[i], yTab[i]);
    }

    final double[] fitted = fitter.fit();
    Assert.assertEquals(a, fitted[0], 7.6e-4);
    Assert.assertEquals(w, fitted[1], 3.5e-3);
    Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1.5e-2);
}
 
Example 16
Source File: AffinityPropagation.java    From clust4j with Apache License 2.0 4 votes vote down vote up
/**
 * Remove this from scope of {@link #fit()} to avoid lots of large objects
 * left in memory. This is more space efficient and promotes easier testing.
 * @param X
 * @param metric
 * @param seed
 * @param addNoise
 * @return the smoothed similarity matrix
 */
protected static double[][] computeSmoothedSimilarity(final double[][] X, GeometricallySeparable metric, Random seed, boolean addNoise) {
	/*
	 * Originally, we computed similarity matrix, then refactored the diagonal vector, and
	 * then computed the following portions. We can do this all at once and save lots of passes
	 * (5?) on the order of O(M^2), condensing it all to one pass of O(M choose 2).
	 * 
	 * After the sim matrix is computed, we need to do three things:
	 * 
	 * 1. Create a matrix of very small values (tiny_scaled) to remove degeneracies in sim_mal
	 * 2. Multiply tiny_scaled by an extremely small value (GlobalState.Mathematics.TINY*100)
	 * 3. Create a noise matrix of random Gaussian values and add it to the similarity matrix.
	 * 
	 * The methods exist to build these in three to five separate O(M^2) passes, but that's 
	 * extremely expensive, so we're going to do it in one giant, convoluted loop. If you're 
	 * trying to debug this, sorry...
	 * 
	 * Total runtime: O(2M * M choose 2)
	 */
	final int m = X.length;
	double[][] sim_mat = new double[m][m];
	
	int idx = 0;
	final double tiny_val = GlobalState.Mathematics.TINY*100;
	final double[] vector = new double[m * m];
	double sim, noise;
	boolean last_iter = false;
	
	
	// Do this a little differently... set the diagonal FIRST.
	for(int i = 0; i < m; i++) {
		sim = -(metric.getPartialDistance(X[i], X[i]));
		sim_mat[i][i] = sim;
		vector[idx++] = sim;
	}
	
	
	for(int i = 0; i < m - 1; i++) {
		for(int j = i + 1; j < m; j++) { // Upper triangular
			sim = -(metric.getPartialDistance(X[i], X[j])); // similarity
			
			// Assign to upper and lower portion
			sim_mat[i][j] = sim;
			sim_mat[j][i] = sim;
			
			// Add to the vector (twice)
			for(int b = 0; b < 2; b++)
				vector[idx++] = sim;
			
			// Catch the last iteration, compute the pref:
			double median = 0.0;
			if(last_iter = (i == m - 2 && j == m - 1))
				median = VecUtils.median(vector);
			
			if(addNoise) {
				noise = (sim * GlobalState.Mathematics.EPS + tiny_val);
				sim_mat[i][j] += (noise * seed.nextGaussian());
				sim_mat[j][i] += (noise * seed.nextGaussian());
				
				if(last_iter) { // set diag and do the noise thing.
					noise = (median * GlobalState.Mathematics.EPS + tiny_val);
					for(int h = 0; h < m; h++)
						sim_mat[h][h] = median + (noise * seed.nextGaussian());
				}
			} else if(last_iter) {
				// it's the last iter and no noise. Just set diag.
				for(int h = 0; h < m; h++)
					sim_mat[h][h] = median;
			}
		}
	}
	
	return sim_mat;
}
 
Example 17
Source File: KalmanTest.java    From KalmanRx with Apache License 2.0 4 votes vote down vote up
@Test
public void random() {

    try {
        JKalman kalman = new JKalman(4, 2);

        Random rand = new Random(System.currentTimeMillis() % 2011);
        double x = 0;
        double y = 0;
        // constant velocity
        double dx = rand.nextDouble();
        double dy = rand.nextDouble();

        // init
        Matrix s = new Matrix(4, 1); // state [x, y, dx, dy, dxy]        
        Matrix c = new Matrix(4, 1); // corrected state [x, y, dx, dy, dxy]

        Matrix m = new Matrix(2, 1); // measurement [x]
        m.set(0, 0, x);
        m.set(1, 0, y);

        // transitions for x, y, dx, dy
        double[][] tr = {{1, 0, 1, 0},
                {0, 1, 0, 1},
                {0, 0, 1, 0},
                {0, 0, 0, 1}};
        kalman.setTransition_matrix(new Matrix(tr));

        // 1s somewhere?
        kalman.setError_cov_post(kalman.getError_cov_post().identity());

        // init first assumption similar to first observation (cheat :)
        // kalman.setState_post(kalman.getState_post());

        // report what happend first :)
        System.out.println("first x:" + x + ", y:" + y + ", dx:" + dx + ", dy:" + dy);
        System.out.println("no; x; y; dx; dy; predictionX; predictionY; predictionDx; predictionDy; correctionX; correctionY; correctionDx; correctionDy;");

        // For debug only
        for (int i = 0; i < 200; ++i) {

            // check state before
            s = kalman.Predict();

            // function init :)
            // m.set(1, 0, rand.nextDouble());
            x = rand.nextGaussian();
            y = rand.nextGaussian();

            m.set(0, 0, m.get(0, 0) + dx + rand.nextGaussian());
            m.set(1, 0, m.get(1, 0) + dy + rand.nextGaussian());

            // a missing value (more then 1/4 times)
            if (rand.nextGaussian() < -0.8) {
                System.out.println("" + i + ";;;;;"
                        + s.get(0, 0) + ";" + s.get(1, 0) + ";" + s.get(2, 0) + ";" + s.get(3, 0) + ";");
            } else { // measurement is ok :)
                // look better
                c = kalman.Correct(m);

                System.out.println("" + i + ";" + m.get(0, 0) + ";" + m.get(1, 0) + ";" + x + ";" + y + ";"
                        + s.get(0, 0) + ";" + s.get(1, 0) + ";" + s.get(2, 0) + ";" + s.get(3, 0) + ";"
                        + c.get(0, 0) + ";" + c.get(1, 0) + ";" + c.get(2, 0) + ";" + c.get(3, 0) + ";");
            }

        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}
 
Example 18
Source File: MPEInferenceExperiments_Deliv1.java    From toolbox with Apache License 2.0 4 votes vote down vote up
private static Assignment randomEvidence(long seed, double evidenceRatio, BayesianNetwork bn) throws UnsupportedOperationException {

        if (evidenceRatio<=0 || evidenceRatio>=1) {
            throw new UnsupportedOperationException("Error: invalid ratio");
        }

        int numVariables = bn.getVariables().getNumberOfVars();

        Random random=new Random(seed); //1823716125
        int numVarEvidence = (int) Math.ceil(numVariables*evidenceRatio); // Evidence on 20% of variables
        //numVarEvidence = 0;
        //List<Variable> varEvidence = new ArrayList<>(numVarEvidence);
        double [] evidence = new double[numVarEvidence];
        Variable aux;
        HashMapAssignment assignment = new HashMapAssignment(numVarEvidence);

        int[] indexesEvidence = new int[numVarEvidence];
        //indexesEvidence[0]=varInterest.getVarID();
        //if (Main.VERBOSE) System.out.println(variable.getVarID());

        if (Main.VERBOSE) System.out.println("Evidence:");
        for( int k=0; k<numVarEvidence; k++ ) {
            int varIndex=-1;
            do {
                varIndex = random.nextInt( bn.getNumberOfVars() );
                //if (Main.VERBOSE) System.out.println(varIndex);
                aux = bn.getVariables().getVariableById(varIndex);

                double thisEvidence;
                if (aux.isMultinomial()) {
                    thisEvidence = random.nextInt( aux.getNumberOfStates() );
                }
                else {
                    thisEvidence = random.nextGaussian();
                }
                evidence[k] = thisEvidence;

            } while (ArrayUtils.contains(indexesEvidence, varIndex) );

            indexesEvidence[k]=varIndex;
            //if (Main.VERBOSE) System.out.println(Arrays.toString(indexesEvidence));
            if (Main.VERBOSE) System.out.println("Variable " + aux.getName() + " = " + evidence[k]);

            assignment.setValue(aux,evidence[k]);
        }
        if (Main.VERBOSE) System.out.println();
        return assignment;
    }
 
Example 19
Source File: Gamma.java    From JSAT with GNU General Public License v3.0 4 votes vote down vote up
@Override
public double[] sample(int numSamples, Random rand) 
{
    /**
     * See: Marsaglia, George, and Wai Wan Tsang. “A Simple Method for
     * Generating Gamma Variables.” ACM Trans. Math. Softw. 26, no. 3
     * (September 2000): 363–72. https://doi.org/10.1145/358407.358414.
     */
    double[] toRet = new double[numSamples];
    
    if (k >= 1.0)
    {
        double d = k - 1.0/3.0;
        double c = 1.0/sqrt(9.0*d);
            
        for(int i = 0; i < toRet.length; i++)
        {
            while(true)
            {
                double x = 0, xSqrd = 0;
                double v = 0;
                while (v <= 0.0)
                {
                    x = rand.nextGaussian();
                    v = 1 + c*x;
                }

                v = v*v*v;
                double u = rand.nextDouble();
                xSqrd = x*x;
                //Squeeze check done first to avoid expensieve logs
                double squeezeCheck = 1.0 - 0.0331 * xSqrd * xSqrd;
                if (u <  squeezeCheck) 
                {
                    toRet[i] = theta*d*v;
                    break;
                }//fail, now try logs if we must
                else if( log(u) < 0.5 * xSqrd + d * (1.0 - v + log(v)))
                {
                    toRet[i] = theta*d*v;
                    break;
                }
            }
        }
    }
    else
    {
        Gamma shifted = new Gamma(k+1, 1.0);
        
        double[] gs = shifted.sample(numSamples, rand);
        for(int i = 0; i < toRet.length; i++)
            toRet[i] = theta*gs[i]*pow(rand.nextDouble(), 1.0/k);
    }
    
    
    return toRet;
}
 
Example 20
Source File: FeatureFixedBinNumericStaticticsTest.java    From geowave with Apache License 2.0 3 votes vote down vote up
@Test
public void testMix2() {

  final FeatureFixedBinNumericStatistics stat =
      new FeatureFixedBinNumericStatistics((short) -1, "pop");

  final Random rand = new Random(7777);

  final double min = 0;
  double max = 0;

  double next = 0;
  for (int i = 0; i < 100000; i++) {
    next = 1000 * rand.nextGaussian();
    stat.entryIngested(create(next));
    max = Math.max(next, max);
  }

  assertEquals(1.0, stat.cdf(max), 0.00001);

  assertEquals(0.5, stat.cdf(0), 0.05);

  assertEquals(100000, sum(stat.count(10)));

  final double r = stat.percentPopulationOverRange(min / 2, max / 2);

  assertEquals(0.5, r, 0.05);

  System.out.println(stat.toString());
}