List of usage examples for java.lang Math random
public static double random()
From source file:io.lightlink.output.JsonStreamTestPerf.java
private HashMap<String, Object> getData() { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("value1", Math.random()); map.put("value2", "" + Math.random()); map.put("value3", "" + Math.random()); map.put("value5", "" + Math.random()); map.put("value6", "" + Math.random()); map.put("value7", "" + Math.random()); map.put("value8", "" + Math.random()); map.put("value9", "" + Math.random()); map.put("value10", "" + Math.random()); return map;/* w ww . jav a 2 s . c o m*/ }
From source file:edu.umass.cs.utils.Util.java
public static boolean oneIn(int n) { return Math.random() < 1.0 / Math.max(1, n) ? true : false; }
From source file:com.github.hdl.tensorflow.yarn.app.ClusterSpec.java
private ClusterSpec(int workerServers, int psServers) { this.setNumTotalParameterServers(psServers); this.setNumTotalWorkerServers(workerServers); workers = new HashMap<>(); paramServers = new HashMap<>(); serverPortNext = PORT_FLOOR + ((int) (Math.random() * (PORT_CEILING - PORT_FLOOR)) + 1); }
From source file:edu.indiana.d2i.htrc.skmeans.StreamingKMeansDriver.java
private void StreamingKMeansConfigHelper(Configuration conf, String input, int maxCluster) throws IOException { // get samples to calculate scale factor FileSystem fs = FileSystem.get(conf); FileStatus[] status = fs.listStatus(new Path(input), Utilities.HIDDEN_FILE_FILTER); int index = 0 + (int) (Math.random() * (status.length)); SequenceFile.Reader seqReader = new SequenceFile.Reader(fs, status[index].getPath(), conf); int count = 0; Text key = new Text(); VectorWritable value = new VectorWritable(); List<MatrixSlice> slices = new ArrayList<MatrixSlice>(); while (seqReader.next(key, value) && count < samplesNum) { MatrixSlice slice = new MatrixSlice(value.get().clone(), count); slices.add(slice);/*from ww w .j av a 2 s .c om*/ count++; } // set cutoff float cutoff = (float) StreamingKmeans.estimateCutoff(slices, samplesNum); conf.setFloat(StreamingKMeansConfigKeys.CUTOFF, cutoff); logger.info("Scale factor (cutoff) is: " + cutoff); // set vector dimension int dim = value.get().size(); conf.setInt(StreamingKMeansConfigKeys.VECTOR_DIMENSION, dim); logger.info("Dimemsion of a vector is: " + dim); // set maximum #cluster conf.setInt(StreamingKMeansConfigKeys.MAXCLUSTER, maxCluster); // set distance measurement conf.set(StreamingKMeansConfigKeys.DIST_MEASUREMENT, EuclideanDistanceMeasure.class.getName()); }
From source file:com.galenframework.ide.model.SizeVariation.java
public List<Dimension> generateVariations() { if (end == null || iterations < 2) { return asList(start.toSeleniumDimension()); } else {//ww w .j a v a2 s . co m List<Dimension> sizes = new LinkedList<>(); int deltaWidth = end.getWidth() - start.getWidth(); int deltaHeight = end.getHeight() - start.getHeight(); int maxDistance = Math.max(Math.abs(deltaWidth), Math.abs(deltaHeight)); int amount = Math.min(maxDistance, iterations); if (amount > 0) { int randomWidthDelta = 0; int randomHeightDelta = 0; for (int i = 0; i < amount; i++) { if (random) { randomWidthDelta = (int) (Math.random() * deltaWidth / amount); randomHeightDelta = (int) (Math.random() * deltaHeight / amount); } int w = (int) Math.floor(start.getWidth() + deltaWidth * i / amount + randomWidthDelta); int h = (int) Math.floor(start.getHeight() + deltaHeight * i / amount + randomHeightDelta); sizes.add(new Dimension(w, h)); } } else { sizes.add(new Dimension(start.getWidth(), start.getHeight())); } return sizes; } }
From source file:com.ciphertool.genetics.algorithms.mutation.ConservativeMutationAlgorithm.java
/** * Performs a genetic mutation of a random Gene of the supplied Chromosome * /*from w w w .j a v a 2 s .c o m*/ * @param chromosome * the Chromosome to mutate */ private Integer mutateRandomGene(Chromosome chromosome, List<Integer> geneIndices) { int randomIndex; // We don't want to reuse an index, so loop until we find a new one int attempts = 0; do { randomIndex = (int) (Math.random() * chromosome.getGenes().size()); attempts++; if (attempts >= MAX_FIND_ATTEMPTS) { if (log.isDebugEnabled()) { log.debug("Unable to find a previously unused Gene index after " + attempts + " attempts. Returning null."); } return null; } } while (geneIndices.contains(randomIndex)); mutateGene(chromosome, randomIndex); return randomIndex; }
From source file:org.dataconservancy.ui.it.support.CreateIdApiRequestIT.java
/** * Generates {@link #countToGenerate} ids, and insures that they are all unique. * * @throws Exception/*from ww w . j a v a 2 s . c o m*/ */ @Test public void testGenerateUniqueIdsSingleThread() throws Exception { long start = Calendar.getInstance().getTimeInMillis(); for (int i = 0; i < countToGenerate; i++) { // Select an ID type to generate, based on a randomized seed. double seed = Math.random(); log.trace("Seed is {}", seed); Types t = selectType(seed, Types.values()); log.trace("Selected type {} with seed value {}", t, seed); // If debugging is enabled, keep track of the number of ids created for each type. if (log.isDebugEnabled()) { if (idTypeDistribution.containsKey(t)) { idTypeDistribution.get(t).getAndAdd(1); } else { idTypeDistribution.put(t, new AtomicInteger(1)); } } // Create an ID, and keep it in a Set. generatedIds.add(reqFactory.createIdApiRequest(t).execute(hc)); } if (log.isDebugEnabled()) { StringBuilder sb = new StringBuilder("ID distribution:\n"); int totalGenerated = 0; for (Types t : Types.values()) { final Integer typeTotal = idTypeDistribution.get(t).get(); totalGenerated += typeTotal; sb.append("Type: ").append(t).append(" Count: ").append(typeTotal).append("\n"); } sb.append("Total generated: ").append(totalGenerated).append("\n"); sb.append("Unique generated: ").append(generatedIds.size()).append("\n"); sb.append("Execution time: ").append(Calendar.getInstance().getTimeInMillis() - start).append(" ms\n"); log.debug(sb.toString()); } // The number of generated IDs (stored in the Set) should equal 'countToGenerate' assertEquals("Expected " + countToGenerate + " to be generated, but the Set contained " + generatedIds.size() + ". Some ids may not have been unique.", countToGenerate, generatedIds.size()); }
From source file:org.jfree.chart.demo.LineChartDemo3.java
/** * Creates a new demo./*from w w w.j a v a2 s . c o m*/ * * @param title the frame title. */ public LineChartDemo3(final String title) { super(title); // create a dataset... final XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < 10; i++) { final XYSeries series = new XYSeries("S" + i); for (int j = 0; j < 10; j++) { series.add(j, Math.random() * 100); } dataset.addSeries(series); } final JFreeChart chart = createChart(dataset); // add the chart to a panel... final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); setContentPane(chartPanel); }
From source file:emlab.domain.factory.ElectricityProducerFactory.java
@Transactional private PowerPlant createPowerPlant(PowerGeneratingTechnology technology, EnergyProducer energyProducer, PowerGridNode location) {/*from w ww.j av a 2s . c o m*/ PowerPlant plant = new PowerPlant().persist(); String label = energyProducer.getName() + " - " + technology.getName(); plant.setName(label); plant.setTechnology(technology); plant.setOwner(energyProducer); plant.setLocation(location); plant.setConstructionStartTime(-(technology.getExpectedLeadtime() + technology.getExpectedPermittime() + Math.round((Math.random() * technology.getExpectedLifetime()))) + 2); // TODO: Why include expected lead // time and permit time? Wouldn't it // be realistic to have some PP in // the pipeline at the start? plant.setActualLeadtime(plant.getTechnology().getExpectedLeadtime()); plant.setActualPermittime(plant.getTechnology().getExpectedPermittime()); plant.setExpectedEndOfLife(plant.getConstructionStartTime() + plant.getActualPermittime() + plant.getActualLeadtime() + plant.getTechnology().getExpectedLifetime()); plant.calculateAndSetActualInvestedCapital(plant.getConstructionStartTime()); plant.calculateAndSetActualEfficiency(plant.getConstructionStartTime()); plant.setDismantleTime(1000); Loan loan = new Loan().persist(); loan.setFrom(energyProducer); loan.setTo(null); double amountPerPayment = determineLoanAnnuities( plant.getActualInvestedCapital() * energyProducer.getDebtRatioOfInvestments(), plant.getTechnology().getDepreciationTime(), energyProducer.getLoanInterestRate()); loan.setAmountPerPayment(amountPerPayment); loan.setTotalNumberOfPayments(plant.getTechnology().getDepreciationTime()); loan.setLoanStartTime(plant.getConstructionStartTime()); loan.setNumberOfPaymentsDone(-plant.getConstructionStartTime());// Some // payments // are // already // made plant.setLoan(loan); return plant; }
From source file:com.espertech.esper.multithread.TestMTContextListenerDispatch.java
private void tryPerformanceDispatch(int numThreads, int numRepeats) throws Exception { MyListener listener = new MyListener(); engine.getEPAdministrator().getStatement("select").addListener(listener); List<Object>[] events = new ArrayList[numThreads]; int eventId = 0; for (int threadNum = 0; threadNum < numThreads; threadNum++) { events[threadNum] = new ArrayList<Object>(); for (int eventNum = 0; eventNum < numRepeats; eventNum++) { // range: 1 to 1000 int partition = (int) (Math.random() * 50); eventId++;//from www .j a va 2s . co m events[threadNum].add(new SupportBean(new Integer(partition).toString(), eventId)); } } ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); Future futures[] = new Future[numThreads]; long startTime = System.currentTimeMillis(); for (int i = 0; i < numThreads; i++) { Callable callable = new SendEventCallable(i, engine, events[i].iterator()); futures[i] = threadPool.submit(callable); } for (Future future : futures) { assertEquals(true, future.get()); } long delta = System.currentTimeMillis() - startTime; threadPool.shutdown(); threadPool.awaitTermination(10, TimeUnit.SECONDS); // print those events not received for (List<Object> eventList : events) { for (Object event : eventList) { if (!listener.getBeans().contains(event)) { log.info("Expected event was not received, event " + event); } } } assertEquals(numRepeats * numThreads, listener.getBeans().size()); assertTrue("delta=" + delta, delta < 500); }