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

The following are Jave code examples for showing how to use nextDouble() of the java.util.Random class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: alevin-svn2   File: RandomCpuResourceGenerator.java   View Source Code Vote up 6 votes
@Override
public List<CpuResource> generate(ArrayList<Object> parameters) {
	ArrayList<CpuResource> resList = new ArrayList<CpuResource>();
	
	NetworkStack ns = (NetworkStack)parameters.get(0);
	Integer minCPU = ConversionHelper.paramObjectToInteger(parameters.get(1));
	Integer maxCPU = ConversionHelper.paramObjectToInteger(parameters.get(2));
	
	Random random = new Random();
	
	
	SubstrateNetwork sn = ns.getSubstrate();
	
	for(SubstrateNode n : sn.getVertices()) {
		CpuResource cpu = new CpuResource(n);
		int value = (int) (minCPU + (maxCPU
				- minCPU + 1)
				* random.nextDouble());
		cpu.setCycles((double) value);
		n.add(cpu);
		resList.add(cpu);
	}
	
	return resList;
}
 
Example 2
Project: HiTSDB-Client   File: TestHiTSDBClientBatchPut.java   View Source Code Vote up 6 votes
@Ignore
@Test
public void testMiddleDateBatchPutDataCallback() {
    Random random = new Random();
    int time = getTime();
    for(int i = 0;i<5500;i++) {
        double nextDouble = random.nextDouble() * 100;
        Point point = Point.metric("test1")
                               .tag("tagk1", "tagv1")
                               .tag("tagk2", "tagv2")
                               .tag("tagk3", "tagv3")
                               .timestamp(time + i).value(nextDouble)
                               .build();
        tsdb.put(point);
    }
}
 
Example 3
Project: GitHub   File: Issue215_double_array.java   View Source Code Vote up 6 votes
public void test_for_issue() throws Exception {
    double[] values = new double[128];
    Random random = new Random();
    for (int i = 0; i < values.length; ++i) {
        values[i] = random.nextDouble();
    }
    
    Map<String, double[]> map = new HashMap<String, double[]>();
    map.put("val", values);
    
    String text = JSON.toJSONString(map);
    System.out.println(text);
    
    Map<String, double[]> map2 = JSON.parseObject(text, new TypeReference<HashMap<String, double[]>>() {});
    double[] values2 = (double[]) map2.get("val");
    Assert.assertTrue(Arrays.equals(values2, values));
}
 
Example 4
Project: powsybl-core   File: Colors.java   View Source Code Vote up 6 votes
public static String[] generateColorScale(int n) {
    if (n <= 0) {
        throw new IllegalArgumentException("Color scale size has to be stricly positive");
    }
    String[] colors = new String[n];
    Random random = new Random();
    for (int i = 0; i < n; i++) {
        double h = random.nextDouble();
        h += GOLDEN_RATIO_CONJUGATE;
        h %= 1;
        long[] rgb = hsvToRgb(h, 0.5, 0.95);
        String hex = String.format("#%02x%02x%02x", rgb[0], rgb[1], rgb[2]).toUpperCase();
        colors[i] = hex;
    }
    return colors;
}
 
Example 5
Project: SpaceExplorer2D   File: PlanetData.java   View Source Code Vote up 5 votes
public PlanetData(long seed, StarData data) {
	this.seed = seed;
	this.star = data;
	plRandom = new Random(seed);
	chRandom = new Random();
	name = generateName(plRandom);
	albedo = plRandom.nextDouble();
	distanceToStar = /*
						 * (Maths.normalStandardDistribution((random.nextDouble() + 0) * 6)) *
						 * (MAXDISSTAR - MINDISSTAR) + MINDISSTAR;
						 */ MINDISSTAR + plRandom.nextDouble() * (MAXDISSTAR - MINDISSTAR);
	radiusMax = (long) (Maths.normalStandardDistribution(plRandom.nextDouble() * 2) * MAX_RADIUS);
	radiusFade = radiusMax - (long) Math.min(Math.max(0, plRandom.nextInt(40) + 10), radiusMax * 0.1);
	daytimePercentage = (float) (plRandom.nextDouble() * 0.6 + 0.2);
	avgLengthOfDay = MINDAYSEC + plRandom.nextInt(MAXDAYSEC - MINDAYSEC);
	timeOffset = plRandom.nextInt(avgLengthOfDay);
	avgTempKelvin = calculateAvgPlanetTemp(star.getLuminosity(), albedo, distanceToStar, daytimePercentage)
			+ (plRandom.nextDouble() * 0.2 + 0.9) * TEMPOFFSET;
	maxTempDifKelvin = MINTEMPDIF
			+ Maths.normalStandardDistribution((1 - plRandom.nextDouble()) * 7) * (MAXTEMPDIF - MINTEMPDIF);
	humidity = plRandom.nextDouble();
	maxDifHumidity = plRandom.nextDouble();

	tempNoise = new NoiseWrapper(new OpenSimplexNoise(seed ^ (long) avgTempKelvin)).setXScale(1 / 300.0)
			.setYScale(1 / 300.0);
	heightsNoise = new NoiseWrapper(new OpenSimplexNoise(seed ^ 0)).setXScale(1 / 100.0).setYScale(1 / 100.0);
	humidityNoise = new NoiseWrapper(new OpenSimplexNoise(seed ^ (long) humidity)).setXScale(1 / 200.0)
			.setYScale(1 / 200.0);

}
 
Example 6
Project: apache-tomcat-7.0.73-with-comment   File: Stockticker.java   View Source Code Vote up 5 votes
@Override
public void run() {
    try {

        Stock[] stocks = new Stock[] { new Stock("GOOG", 435.43),
                new Stock("YHOO", 27.88), new Stock("ASF", 1015.55), };
        Random r = new Random(System.currentTimeMillis());
        while (run) {
            for (int j = 0; j < 1; j++) {
                int i = r.nextInt() % 3;
                if (i < 0)
                    i = i * (-1);
                Stock stock = stocks[i];
                double change = r.nextDouble();
                boolean plus = r.nextBoolean();
                if (plus) {
                    stock.setValue(stock.getValue() + change);
                } else {
                    stock.setValue(stock.getValue() - change);
                }
                stock.setCnt(++ticknr);
                for (TickListener l : listeners) {
                    l.tick(stock);
                }

            }
            Thread.sleep(850);
        }
    } catch (InterruptedException ix) {
        // Ignore
    } catch (Exception x) {
        x.printStackTrace();
    }
}
 
Example 7
Project: BUbiNG   File: TestUtil.java   View Source Code Vote up 5 votes
/** Returns a random vector of given size, using the provided {@link java.util.Random} object.
 *
 *  @param n the vector size.
 *  @param random the random number generator to be used (its {@link Random#nextDouble()} method will be called).
 */
public static double[] randomDoubleVector(final int n, final Random random) {
	double[] a = new double[n];
	for (int i = 0; i < n; i++)
			a[i] = random.nextDouble();
	return a;
}
 
Example 8
Project: ProjectAres   File: FiniteBlockRegion.java   View Source Code Vote up 5 votes
@Override
public Vector getRandom(Random random) {
    final BlockVector randomBlock = positions.chooseRandom(random);
    double dx = random.nextDouble();
    double dy = random.nextDouble();
    double dz = random.nextDouble();
    return randomBlock.add(dx, dy, dz);
}
 
Example 9
Project: Proj4   File: Vector2D.java   View Source Code Vote up 5 votes
/**
 * Create a random vector with a magnitude no greater than specified
 * @param rand The source of randomness to use.
 * @param maxMagnitude
 * @return A new random Vector2D
 */
public static Vector2D getRandom(Random rand, double maxMagnitude) {
    final double max = maxMagnitude * maxMagnitude;

    final double x2 = rand.nextDouble() * max;
    final double y2 = rand.nextDouble() * (max - x2);

    final double x = rand.nextBoolean() ? (double)Math.sqrt(x2) : -(double)Math.sqrt(x2);
    final double y = rand.nextBoolean() ? (double)Math.sqrt(y2) : -(double)Math.sqrt(y2);

    return new Vector2D(x, y);
}
 
Example 10
Project: OpenJSharp   File: EmergencySoundbank.java   View Source Code Vote up 5 votes
public static SF2Layer new_bell(SF2Soundbank sf2) {
    Random random = new Random(102030201);
    int x = 8;
    int fftsize = 4096 * x;
    double[] data = new double[fftsize * 2];
    double base = x * 25;
    double start_w = 0.01;
    double end_w = 0.05;
    double start_a = 0.2;
    double end_a = 0.00001;
    double a = start_a;
    double a_step = Math.pow(end_a / start_a, 1.0 / 40.0);
    for (int i = 0; i < 40; i++) {
        double detune = 1 + (random.nextDouble() * 2 - 1) * 0.01;
        double w = start_w + (end_w - start_w) * (i / 40.0);
        complexGaussianDist(data, base * (i + 1) * detune, w, a);
        a *= a_step;
    }
    SF2Sample sample = newSimpleFFTSample(sf2, "EPiano", data, base);
    SF2Layer layer = newLayer(sf2, "EPiano", sample);
    SF2Region region = layer.getRegions().get(0);
    region.putInteger(SF2Region.GENERATOR_SAMPLEMODES, 1);
    region.putInteger(SF2Region.GENERATOR_ATTACKVOLENV, -12000);
    region.putInteger(SF2Region.GENERATOR_RELEASEVOLENV, 0);
    region.putInteger(SF2Region.GENERATOR_DECAYVOLENV, 4000);
    region.putInteger(SF2Region.GENERATOR_SUSTAINVOLENV, 1000);
    region.putInteger(SF2Region.GENERATOR_ATTACKMODENV, 1200);
    region.putInteger(SF2Region.GENERATOR_RELEASEMODENV, 12000);
    region.putInteger(SF2Region.GENERATOR_MODENVTOFILTERFC, -9000);
    region.putInteger(SF2Region.GENERATOR_INITIALFILTERFC, 16000);
    return layer;
}
 
Example 11
Project: incubator-netbeans   File: RandomTextProvider.java   View Source Code Vote up 5 votes
public char randomChar(Random random) {
    double r = random.nextDouble() * ratioSum;
    for (int i = 0; i < randomCharDescriptors.length; i++) {
        RandomCharDescriptor descriptor = randomCharDescriptors[i];
        if ((r -= descriptor.ratio()) < 0) {
            return descriptor.randomChar(random);
        }
    }
    // Internal error - randomCharAvailable() needs to be checked
    throw new IllegalStateException("No random char descriptions available");
}
 
Example 12
Project: BUbiNG   File: URLRespectsRobotsTest.java   View Source Code Vote up 5 votes
@Test
public void testPrefixesDeep() {
	Set<String> inset = new ObjectOpenHashSet<>();
	Set<String> pfset = new ObjectOpenHashSet<>();
	Random rand = new Random(0);
	for (int i = 100; i < 999; i++) {
		if (rand.nextDouble() < 0.3) {
			String commonPref = String.valueOf(i);
			boolean putPrefix = rand.nextDouble() < 0.9;
			if (putPrefix) {
				pfset.add(commonPref);
				inset.add(commonPref);
			}
			for (int j = 100; j < 450; j++) {
				if (rand.nextDouble() < 0.3) {
					inset.add(commonPref + j);
					if (! putPrefix) pfset.add(commonPref + j);
				}
			}
		}
	}
	char[][] resultArray = URLRespectsRobots.toSortedPrefixFreeCharArrays(inset);
	Set<String> result = new ObjectOpenHashSet<>();
	for (char[] a: resultArray) result.add(new String(a));
	assertEquals(result, pfset);


}
 
Example 13
Project: AI-RRT-Motion-Planning   File: Main.java   View Source Code Vote up 5 votes
private static void getStartPosition(double[] position, Test tester) {
    Random randP = new Random();
    Point2D p = new Point2D.Double(randP.nextDouble(), randP.nextDouble());
    List<Obstacle> obs = tester.ps.obstacles;
    while (containPoint(obs, p)) {
        p = new Point2D.Double(randP.nextDouble(), randP.nextDouble());
    }
    position[0] = p.getX();
    position[1] = p.getY();
}
 
Example 14
Project: jdk8u-jdk   File: EmergencySoundbank.java   View Source Code Vote up 5 votes
public static SF2Layer new_open_hihat(SF2Soundbank sf2) {
    double datah[];
    {
        int fftlen = 4096 * 4;
        double[] data = new double[2 * fftlen];
        Random random = new Random(3049912);
        for (int i = 0; i < data.length; i += 2)
            data[i] = (2.0 * (random.nextDouble() - 0.5));
        for (int i = fftlen / 2; i < data.length; i++)
            data[i] = 0;
        for (int i = 0; i < 200; i++)
            data[i] = 0;
        for (int i = 0; i < 2048 * 4; i++) {
            double gain = (i / (2048.0 * 4.0));
            data[i] = gain;
        }
        datah = data;
    }

    SF2Sample sample = newSimpleFFTSample(sf2, "Open Hi-Hat", datah, 1000, 5);

    SF2Layer layer = new SF2Layer(sf2);
    layer.setName("Open Hi-Hat");

    SF2GlobalRegion global = new SF2GlobalRegion();
    layer.setGlobalZone(global);
    sf2.addResource(layer);

    SF2LayerRegion region = new SF2LayerRegion();
    region.putInteger(SF2Region.GENERATOR_DECAYVOLENV, 1500);
    region.putInteger(SF2Region.GENERATOR_SAMPLEMODES, 1);
    region.putInteger(SF2Region.GENERATOR_RELEASEVOLENV, 1500);
    region.putInteger(SF2Region.GENERATOR_SUSTAINVOLENV, 1000);
    region.putInteger(SF2Region.GENERATOR_SCALETUNING, 0);
    region.putInteger(SF2Region.GENERATOR_EXCLUSIVECLASS, 1);
    region.setSample(sample);
    layer.getRegions().add(region);

    return layer;
}
 
Example 15
Project: HiTSDB-Client   File: TestHiTSDBClientBatchPutNoLogic.java   View Source Code Vote up 5 votes
@Test
public void testLitterDateBatchPutDataCallback() {
    Random random = new Random();
    int time = getTime();
    for(int i = 0;i<4000;i++) {
        double nextDouble = random.nextDouble() * 100;
        Point point = Point.metric("test1")
                               .tag("tagk1", "tagv1")
                               .tag("tagk2", "tagv2")
                               .tag("tagk3", "tagv3")
                               .timestamp(time + i).value(nextDouble)
                               .build();
        tsdb.put(point);
    }
}
 
Example 16
Project: NeuralNetworksLite   File: RandomGenerator.java   View Source Code Vote up 5 votes
public static int binomial(int n, double p, Random rng) {
	if (p < 0 || p > 1) return 0;
	int c = 0;
	double r;
	for(int i = 0; i < n; i++) {
           r = rng.nextDouble();
           if (r < p) c++;
       }
       return c;
}
 
Example 17
Project: weak-semi-crf-naacl2016   File: GlobalNetworkParam.java   View Source Code Vote up 4 votes
public void lockItAndKeepExistingFeatureWeights(){
	Random r = new Random(NetworkConfig.RANDOM_INIT_FEATURE_SEED);
	
	if(this.isLocked()) return;
	
	if(NetworkConfig.TRAIN_MODE_IS_GENERATIVE){
		this.expandFeaturesForGenerativeModelDuringTesting();
	}
	
	double[] weights_new = new double[this._size];
	this._counts = new double[this._size];
	for(int k = 0; k<this._weights.length; k++){
		weights_new[k] = this._weights[k];
	}
	for(int k = this._weights.length ; k<this._size; k++){
		weights_new[k] = NetworkConfig.RANDOM_INIT_WEIGHT ? (r.nextDouble()-.5)/10 :
			NetworkConfig.FEATURE_INIT_WEIGHT;
	}
	this._weights = weights_new;
	this.resetCountsAndObj();
	
	this._feature2rep = new String[this._size][];
	Iterator<String> types = this._featureIntMap.keySet().iterator();
	while(types.hasNext()){
		String type = types.next();
		HashMap<String, HashMap<String, Integer>> output2input = this._featureIntMap.get(type);
		Iterator<String> outputs = output2input.keySet().iterator();
		while(outputs.hasNext()){
			String output = outputs.next();
			HashMap<String, Integer> input2id = output2input.get(output);
			Iterator<String> inputs = input2id.keySet().iterator();
			while(inputs.hasNext()){
				String input = inputs.next();
				int id = input2id.get(input);
				this._feature2rep[id] = new String[]{type, output, input};
			}
		}
	}
	this._version = 0;
	this._opt = this._optFactory.create(this._weights.length, getFeatureIntMap());
	this._locked = true;
	
	System.err.println(this._size+" features.");
	
}
 
Example 18
Project: elasticsearch_my   File: RandomDocumentPicks.java   View Source Code Vote up 4 votes
private static Object randomFieldValue(Random random, int currentDepth) {
    switch(RandomNumbers.randomIntBetween(random, 0, 9)) {
        case 0:
            return randomString(random);
        case 1:
            return random.nextInt();
        case 2:
            return random.nextBoolean();
        case 3:
            return random.nextDouble();
        case 4:
            List<String> stringList = new ArrayList<>();
            int numStringItems = RandomNumbers.randomIntBetween(random, 1, 10);
            for (int j = 0; j < numStringItems; j++) {
                stringList.add(randomString(random));
            }
            return stringList;
        case 5:
            List<Integer> intList = new ArrayList<>();
            int numIntItems = RandomNumbers.randomIntBetween(random, 1, 10);
            for (int j = 0; j < numIntItems; j++) {
                intList.add(random.nextInt());
            }
            return intList;
        case 6:
            List<Boolean> booleanList = new ArrayList<>();
            int numBooleanItems = RandomNumbers.randomIntBetween(random, 1, 10);
            for (int j = 0; j < numBooleanItems; j++) {
                booleanList.add(random.nextBoolean());
            }
            return booleanList;
        case 7:
            List<Double> doubleList = new ArrayList<>();
            int numDoubleItems = RandomNumbers.randomIntBetween(random, 1, 10);
            for (int j = 0; j < numDoubleItems; j++) {
                doubleList.add(random.nextDouble());
            }
            return doubleList;
        case 8:
            Map<String, Object> newNode = new HashMap<>();
            addRandomFields(random, newNode, ++currentDepth);
            return newNode;
        case 9:
            byte[] byteArray = new byte[RandomNumbers.randomIntBetween(random, 1, 1024)];
            random.nextBytes(byteArray);
            return byteArray;
        default:
            throw new UnsupportedOperationException();
    }
}
 
Example 19
Project: openjdk-jdk10   File: EmergencySoundbank.java   View Source Code Vote up 4 votes
public static SF2Layer new_reverse_cymbal(SF2Soundbank sf2) {
    double datah[];
    {
        int fftlen = 4096 * 4;
        double[] data = new double[2 * fftlen];
        Random random = new Random(3049912);
        for (int i = 0; i < data.length; i += 2)
            data[i] = (2.0 * (random.nextDouble() - 0.5));
        for (int i = fftlen / 2; i < data.length; i++)
            data[i] = 0;
        for (int i = 0; i < 100; i++)
            data[i] = 0;

        for (int i = 0; i < 512 * 2; i++) {
            double gain = (i / (512.0 * 2.0));
            data[i] = 1 - gain;
        }
        datah = data;
    }

    SF2Sample sample = newSimpleFFTSample(sf2, "Reverse Cymbal",
            datah, 100, 20);

    SF2Layer layer = new SF2Layer(sf2);
    layer.setName("Reverse Cymbal");

    SF2GlobalRegion global = new SF2GlobalRegion();
    layer.setGlobalZone(global);
    sf2.addResource(layer);

    SF2LayerRegion region = new SF2LayerRegion();
    region.putInteger(SF2Region.GENERATOR_ATTACKVOLENV, -200);
    region.putInteger(SF2Region.GENERATOR_DECAYVOLENV, -12000);
    region.putInteger(SF2Region.GENERATOR_SAMPLEMODES, 1);
    region.putInteger(SF2Region.GENERATOR_RELEASEVOLENV, -1000);
    region.putInteger(SF2Region.GENERATOR_SUSTAINVOLENV, 1000);
    region.setSample(sample);
    layer.getRegions().add(region);

    return layer;
}
 
Example 20
Project: OptimizationAlgorithms   File: SimulatedAnnealing.java   View Source Code Vote up 4 votes
public void solve(OptimizationProblem op, SimulatedAnnealingStrategy strategy , boolean maximize){

        State currentState = op.initialState();

        //Set initial temp
        double temp = 100000;

        while(temp > 1){

            //Get Neighbours
            ArrayList<Pair<State,Action>> neighbours = new ArrayList<>();
            for(Action act : op.actions(currentState)){
                for(State target : op.result(currentState,act)) {
                    neighbours.add(new Pair(target,act));
                }
            }

            int curval = op.eval(currentState);
            //boolean isFound = false;

            Random rnd = new Random();
            int index = rnd.nextInt(neighbours.size());
            Pair<State,Action> psa = neighbours.get(index);

            int tval = op.eval(psa.getKey());
            double p = acceptanceProbability(curval,tval,temp,maximize);
            double d = rnd.nextDouble();
            //System.out.println(p + " ! " + d);
            if(p > d){
                currentState = psa.getKey();
                solution.add(psa.getValue());
                System.out.println("[SA] Eval : " + tval);
            }

            if(strategy == SimulatedAnnealingStrategy.EXPOTENTIAL) {

                //cool system
                temp *= 1 - coolingRate;

            }else if(strategy == SimulatedAnnealingStrategy.LINEAR_TEMPERATURE) {

                temp -= coolingRate;

            }else if(strategy == SimulatedAnnealingStrategy.RANDOM_REDUCE){

                temp -= rnd.nextDouble() * coolingRate;

            }else{

                System.err.println("Invalid Strategy !");
                return;
            }

            finalState = currentState;

        }

    }