List of usage examples for java.util Random nextDouble
public double nextDouble()
From source file:de.tudarmstadt.ukp.dkpro.wsd.si.dictionary.util.AbstractDictionary.java
public Map<String, Double> getRandomnylWeightedSenses(String sod) { Random random = new Random(); Map<String, Double> weightedSenses = new HashMap<String, Double>(); for (String[] sense : getTargetValuePairs(sod)) { weightedSenses.put(sense[0], random.nextDouble()); }//from w w w . j av a 2 s.co m return weightedSenses; }
From source file:playground.christoph.dissertation.MultiModalDemo.java
private static void createPopulation(Scenario scenario) { // MatsimRandom.reset(); Random random = MatsimRandom.getLocalInstance(); // Draw some more random numbers to get a better 50:50 share if the initial mode is chosen randomly. for (int i = 0; i < 2046; i++) random.nextInt();/*from w ww . java2 s. c om*/ Map<Id, Double> departureTimes = new HashMap<Id, Double>(); for (int hour = 0; hour < hours; hour++) { for (int i = 0; i < numPersonsPerHour; i++) { String sex; if (random.nextDouble() > 0.5) sex = "f"; else sex = "m"; int age = 18 + random.nextInt(82); Id<Person> personId = Id.create(String.valueOf(hour * numPersonsPerHour + i), Person.class); double departureTime = 8 * 3600 + hour * 3600 + random.nextInt(3600); departureTimes.put(personId, departureTime); Person person = createPerson(scenario, personId, sex, age); scenario.getPopulation().addPerson(person); } } // create and add plans for (Person person : scenario.getPopulation().getPersons().values()) { double departureTime = departureTimes.get(person.getId()); if (createPlansForAllModes) { for (String legMode : CollectionUtils.stringToArray(legModes)) { Plan plan = createPlan(scenario, departureTime, legMode); person.addPlan(plan); if (legMode.equals(initialLegMode)) ((PersonImpl) person).setSelectedPlan(plan); } if (initialLegMode.equals(randomMode)) ((PersonImpl) person) .setSelectedPlan(new RandomPlanSelector<Plan, Person>().selectPlan((person))); } else { if (initialLegMode.equals(randomMode)) { String[] modes = CollectionUtils.stringToArray(legModes); Plan plan = createPlan(scenario, departureTime, modes[random.nextInt(modes.length)]); person.addPlan(plan); } else { Plan plan = createPlan(scenario, departureTime, initialLegMode); person.addPlan(plan); } } } }
From source file:common.matrix.GaussianProbaTest.java
@Test public void MultinomialTest() { final Graph graph = new GraphBuilder().withPlugin(new MLXPlugin()).withScheduler(new NoopScheduler()) .build();/*from ww w . ja va2 s. c om*/ graph.connect(new Callback<Boolean>() { @Override public void on(Boolean result) { GaussianMixtureNode gaussianNodeLive = (GaussianMixtureNode) graph.newTypedNode(0, 0, GaussianMixtureNode.NAME); gaussianNodeLive.set(GaussianMixtureNode.FROM, "f1;f2"); int test = 100; int feat = 2; double[][] b = new double[test][feat]; double[] v = new double[feat]; Random random = new Random(); for (int i = 0; i < test; i++) { for (int j = 0; j < feat; j++) { v[j] = random.nextDouble() * (1 + 100 * j); b[i][j] = v[j]; } gaussianNodeLive.set("f1", b[i][0]); gaussianNodeLive.set("f2", b[i][1]); gaussianNodeLive.learn(new Callback<Boolean>() { @Override public void on(Boolean result) { } }); } double[] ravg = gaussianNodeLive.getAvg(); Matrix rcovData = gaussianNodeLive.getCovariance(ravg, null); double[][] temp = new double[rcovData.rows()][]; for (int i = 0; i < rcovData.rows(); i++) { temp[i] = new double[rcovData.columns()]; for (int j = 0; j < rcovData.columns(); j++) { temp[i][j] = rcovData.get(i, j); } } //Test probability calculation. MultivariateNormalDistribution apache = new MultivariateNormalDistribution(ravg, temp); double eps = 1e-8; double d = apache.density(v); //System.out.println("apache: " + d); double y = gaussianNodeLive.getProbability(v, null, false); //System.out.println("live: " + y); Assert.assertTrue(Math.abs(d - y) < eps); } }); }
From source file:org.canova.api.util.MathUtils.java
/** * Rounds a double to the next nearest integer value in a probabilistic * fashion (e.g. 0.8 has a 20% chance of being rounded down to 0 and a * 80% chance of being rounded up to 1). In the limit, the average of * the rounded numbers generated by this procedure should converge to * the original double./*from w ww . jav a 2 s . c om*/ * * @param value the double value * @param rand the random number generator * @return the resulting integer value */ public static int probRound(double value, Random rand) { if (value >= 0) { double lower = Math.floor(value); double prob = value - lower; if (rand.nextDouble() < prob) { return (int) lower + 1; } else { return (int) lower; } } else { double lower = Math.floor(Math.abs(value)); double prob = Math.abs(value) - lower; if (rand.nextDouble() < prob) { return -((int) lower + 1); } else { return -(int) lower; } } }
From source file:com.ibm.bi.dml.runtime.matrix.data.LibMatrixDatagen.java
/** * /*from w w w.ja va2 s . c o m*/ * @param nrow * @param ncol * @param brlen * @param bclen * @param sparsity * @return * @throws DMLRuntimeException */ public static long[] computeNNZperBlock(long nrow, long ncol, int brlen, int bclen, double sparsity) throws DMLRuntimeException { int numBlocks = (int) (Math.ceil((double) nrow / brlen) * Math.ceil((double) ncol / bclen)); //System.out.println("nrow=" + nrow + ", brlen=" + brlen + ", ncol="+ncol+", bclen=" + bclen + "::: " + Math.ceil(nrow/brlen)); // CURRENT: // Total #of NNZ is set to the expected value (nrow*ncol*sparsity). // TODO: // Instead of using the expected value, one should actually // treat NNZ as a random variable and accordingly generate a random value. long nnz = (long) Math.ceil(nrow * (ncol * sparsity)); //System.out.println("Number of blocks = " + numBlocks + "; NNZ = " + nnz); if (numBlocks > Integer.MAX_VALUE) { throw new DMLRuntimeException( "A random matrix of size [" + nrow + "," + ncol + "] can not be created. Number of blocks (" + numBlocks + ") exceeds the maximum integer size. Try to increase the block size."); } // Compute block-level NNZ long[] ret = new long[numBlocks]; Arrays.fill(ret, 0); if (nnz < numBlocks) { // Ultra-sparse matrix // generate the number of blocks with at least one non-zero // = a random number between [1,nnz] Random runif = new Random(System.nanoTime()); int numNZBlocks = 1; if (nnz - 1 > 0) numNZBlocks += runif.nextInt((int) (nnz - 1)); // To avoid exception from random.nextInt(0) // distribute non-zeros across numNZBlocks // compute proportions for each nzblock // - divide (0,1] interval into numNZBlocks portions of random size double[] blockNNZproportions = new double[numNZBlocks]; runif.setSeed(System.nanoTime()); for (int i = 0; i < numNZBlocks - 1; i++) { blockNNZproportions[i] = runif.nextDouble(); } blockNNZproportions[numNZBlocks - 1] = 1; // sort the values in ascending order Arrays.sort(blockNNZproportions); // compute actual number of non zeros per block according to proportions long actualnnz = 0; int bid; runif.setSeed(System.nanoTime()); for (int i = 0; i < numNZBlocks; i++) { bid = -1; do { bid = runif.nextInt(numBlocks); } while (ret[bid] != 0); double prop = (i == 0 ? blockNNZproportions[i] : (blockNNZproportions[i] - blockNNZproportions[i - 1])); ret[bid] = (long) Math.floor(prop * nnz); actualnnz += ret[bid]; } // Code to make sure exact number of non-zeros are generated while (actualnnz < nnz) { bid = runif.nextInt(numBlocks); ret[bid]++; actualnnz++; } } else { int bid = 0; //long actualnnz = 0; for (long r = 0; r < nrow; r += brlen) { long curBlockRowSize = Math.min(brlen, (nrow - r)); for (long c = 0; c < ncol; c += bclen) { long curBlockColSize = Math.min(bclen, (ncol - c)); ret[bid] = (long) (curBlockRowSize * curBlockColSize * sparsity); //actualnnz += ret[bid]; bid++; } } } return ret; }
From source file:org.orekit.frames.FrameTest.java
private Transform randomTransform(Random random) { Transform transform = Transform.IDENTITY; for (int i = random.nextInt(10); i > 0; --i) { if (random.nextBoolean()) { Vector3D u = new Vector3D(random.nextDouble() * 1000.0, random.nextDouble() * 1000.0, random.nextDouble() * 1000.0); transform = new Transform(transform.getDate(), transform, new Transform(transform.getDate(), u)); } else {// w w w .j ava 2s .c o m double q0 = random.nextDouble() * 2 - 1; double q1 = random.nextDouble() * 2 - 1; double q2 = random.nextDouble() * 2 - 1; double q3 = random.nextDouble() * 2 - 1; double q = FastMath.sqrt(q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3); Rotation r = new Rotation(q0 / q, q1 / q, q2 / q, q3 / q, false); transform = new Transform(transform.getDate(), transform, new Transform(transform.getDate(), r)); } } return transform; }
From source file:org.basketball.MyKMeansPlusPlusClusterer.java
/** * Use K-means++ to choose the initial centers. * * @param <T> type of the points to cluster * @param points the points to choose the initial centers from * @param k the number of centers to choose * @param random random generator to use * @return the initial centers/* ww w . j a v a 2 s. c om*/ */ private static <T extends Clusterable<T>> List<Cluster<T>> chooseInitialCenters(final Collection<T> points, final int k, final Random random) { final List<T> pointSet = new ArrayList<T>(points); final List<Cluster<T>> resultSet = new ArrayList<Cluster<T>>(); // Choose one center uniformly at random from among the data points. final T firstPoint = pointSet.remove(random.nextInt(pointSet.size())); resultSet.add(new Cluster<T>(firstPoint)); final double[] dx2 = new double[pointSet.size()]; while (resultSet.size() < k) { // For each data point x, compute D(x), the distance between x and // the nearest center that has already been chosen. int sum = 0; for (int i = 0; i < pointSet.size(); i++) { final T p = pointSet.get(i); final Cluster<T> nearest = getNearestCluster(resultSet, p); final double d = p.distanceFrom(nearest.getCenter()); sum += d * d; dx2[i] = sum; } // Add one new data point as a center. Each point x is chosen with // probability proportional to D(x)2 final double r = random.nextDouble() * sum; for (int i = 0; i < dx2.length; i++) { if (dx2[i] >= r) { final T p = pointSet.remove(i); resultSet.add(new Cluster<T>(p)); break; } } } return resultSet; }
From source file:org.nd4j.linalg.Nd4jTestsComparisonFortran.java
@Test public void testGemmWithOpsCommonsMath() { List<Pair<INDArray, String>> first = NDArrayCreationUtil.getAllTestMatricesWithShape(3, 5, SEED); List<Pair<INDArray, String>> firstT = NDArrayCreationUtil.getAllTestMatricesWithShape(5, 3, SEED); List<Pair<INDArray, String>> second = NDArrayCreationUtil.getAllTestMatricesWithShape(5, 4, SEED); List<Pair<INDArray, String>> secondT = NDArrayCreationUtil.getAllTestMatricesWithShape(4, 5, SEED); double[] alpha = { 1.0, -0.5, 2.5 }; double[] beta = { 0.0, -0.25, 1.5 }; INDArray cOrig = Nd4j.create(new int[] { 3, 4 }); Random r = new Random(12345); for (int i = 0; i < cOrig.size(0); i++) { for (int j = 0; j < cOrig.size(1); j++) { cOrig.putScalar(new int[] { i, j }, r.nextDouble()); }/* w w w .j a v a2 s. com*/ } for (int i = 0; i < first.size(); i++) { for (int j = 0; j < second.size(); j++) { for (int k = 0; k < alpha.length; k++) { for (int m = 0; m < beta.length; m++) { System.out.println((String.format("Running iteration %d %d %d %d", i, j, k, m))); INDArray cff = Nd4j.create(cOrig.shape(), 'f'); cff.assign(cOrig); INDArray cft = Nd4j.create(cOrig.shape(), 'f'); cft.assign(cOrig); INDArray ctf = Nd4j.create(cOrig.shape(), 'f'); ctf.assign(cOrig); INDArray ctt = Nd4j.create(cOrig.shape(), 'f'); ctt.assign(cOrig); double a = alpha[k]; double b = beta[k]; Pair<INDArray, String> p1 = first.get(i); Pair<INDArray, String> p1T = firstT.get(i); Pair<INDArray, String> p2 = second.get(j); Pair<INDArray, String> p2T = secondT.get(j); String errorMsgff = getGemmErrorMsg(i, j, false, false, a, b, p1, p2); String errorMsgft = getGemmErrorMsg(i, j, false, true, a, b, p1, p2T); String errorMsgtf = getGemmErrorMsg(i, j, true, false, a, b, p1T, p2); String errorMsgtt = getGemmErrorMsg(i, j, true, true, a, b, p1T, p2T); assertTrue(errorMsgff, CheckUtil.checkGemm(p1.getFirst(), p2.getFirst(), cff, false, false, a, b, 1e-4, 1e-6)); assertTrue(errorMsgft, CheckUtil.checkGemm(p1.getFirst(), p2T.getFirst(), cft, false, true, a, b, 1e-4, 1e-6)); assertTrue(errorMsgtf, CheckUtil.checkGemm(p1T.getFirst(), p2.getFirst(), ctf, true, false, a, b, 1e-4, 1e-6)); assertTrue(errorMsgtt, CheckUtil.checkGemm(p1T.getFirst(), p2T.getFirst(), ctt, true, true, a, b, 1e-4, 1e-6)); } } } } }
From source file:com.espertech.esper.example.servershellclient.ServerShellClientMain.java
public ServerShellClientMain() throws Exception { log.info("Loading properties"); Properties properties = new Properties(); InputStream propertiesIS = ServerShellClientMain.class.getClassLoader() .getResourceAsStream(ServerShellConstants.CONFIG_FILENAME); if (propertiesIS == null) { throw new RuntimeException( "Properties file '" + ServerShellConstants.CONFIG_FILENAME + "' not found in classpath"); }// w w w . j a va 2 s . com properties.load(propertiesIS); // Attached via JMX to running server log.info("Attach to server via JMX"); JMXServiceURL url = new JMXServiceURL(properties.getProperty(ServerShellConstants.MGMT_SERVICE_URL)); JMXConnector jmxc = JMXConnectorFactory.connect(url, null); MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); ObjectName mBeanName = new ObjectName(ServerShellConstants.MGMT_MBEAN_NAME); EPServiceProviderJMXMBean proxy = (EPServiceProviderJMXMBean) MBeanServerInvocationHandler .newProxyInstance(mbsc, mBeanName, EPServiceProviderJMXMBean.class, true); // Connect to JMS log.info("Connecting to JMS server"); String factory = properties.getProperty(ServerShellConstants.JMS_CONTEXT_FACTORY); String jmsurl = properties.getProperty(ServerShellConstants.JMS_PROVIDER_URL); String connFactoryName = properties.getProperty(ServerShellConstants.JMS_CONNECTION_FACTORY_NAME); String user = properties.getProperty(ServerShellConstants.JMS_USERNAME); String password = properties.getProperty(ServerShellConstants.JMS_PASSWORD); String destination = properties.getProperty(ServerShellConstants.JMS_INCOMING_DESTINATION); boolean isTopic = Boolean.parseBoolean(properties.getProperty(ServerShellConstants.JMS_IS_TOPIC)); JMSContext jmsCtx = JMSContextFactory.createContext(factory, jmsurl, connFactoryName, user, password, destination, isTopic); // Create statement via JMX log.info("Creating a statement via Java Management Extensions (JMX) MBean Proxy"); proxy.createEPL("select * from SampleEvent where duration > 9.9", "filterStatement", new ClientSideUpdateListener()); // Get producer jmsCtx.getConnection().start(); MessageProducer producer = jmsCtx.getSession().createProducer(jmsCtx.getDestination()); Random random = new Random(); String[] ipAddresses = { "127.0.1.0", "127.0.2.0", "127.0.3.0", "127.0.4.0" }; NumberFormat format = NumberFormat.getInstance(); // Send messages for (int i = 0; i < 1000; i++) { String ipAddress = ipAddresses[random.nextInt(ipAddresses.length)]; double duration = 10 * random.nextDouble(); String durationStr = format.format(duration); String payload = ipAddress + "," + durationStr; BytesMessage bytesMessage = jmsCtx.getSession().createBytesMessage(); bytesMessage.writeBytes(payload.getBytes()); bytesMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); producer.send(bytesMessage); if (i % 100 == 0) { log.info("Sent " + i + " messages"); } } // Create statement via JMX log.info("Destroing statement via Java Management Extensions (JMX) MBean Proxy"); proxy.destroy("filterStatement"); log.info("Shutting down JMS client connection"); jmsCtx.destroy(); log.info("Exiting"); System.exit(-1); }
From source file:AirplaneSettings.java
public double newGround(double gnd) { Random rand = new Random(); double num = rand.nextDouble() * terrain; int odd = rand.nextInt(2); if (odd == 0) num = 0 - num;/*ww w. j a v a 2s . c o m*/ gnd += num; return gnd; }