List of usage examples for java.util Random nextDouble
public double nextDouble()
From source file:org.broadinstitute.gatk.tools.walkers.variantrecalibration.MultivariateGaussian.java
public void initializeRandomSigma(final Random rand) { final double[][] randSigma = new double[mu.length][mu.length]; for (int iii = 0; iii < mu.length; iii++) { for (int jjj = iii; jjj < mu.length; jjj++) { randSigma[jjj][iii] = 0.55 + 1.25 * rand.nextDouble(); if (rand.nextBoolean()) { randSigma[jjj][iii] *= -1.0; }/*from ww w .ja va2s. c o m*/ if (iii != jjj) { randSigma[iii][jjj] = 0.0; } // Sigma is a symmetric, positive-definite matrix created by taking a lower diagonal matrix and multiplying it by its transpose } } Matrix tmp = new Matrix(randSigma); tmp = tmp.times(tmp.transpose()); sigma.setMatrix(0, mu.length - 1, 0, mu.length - 1, tmp); }
From source file:br.com.dropegroup.dprf.dao.mock.OcorrenciaMockDAO.java
public OcorrenciaMockDAO() { // dados de teste Random r = new Random(); oaVoList = new ArrayList<OcorrenciaAgrupamentoVO>(); for (String rodovia : Arrays.asList("BR-110", "BR-116")) { for (String estado : Arrays.asList("SP", "RJ", "MG", "ES", "PR", "SC", "RS")) { for (int ano = 2007; ano <= 2013; ano++) { for (int mes = 1; mes <= 12; mes++) { oaVoList.add(buildVO(rodovia, estado, ano, mes, r.nextDouble())); }/* w ww . j av a2 s . co m*/ } } } }
From source file:com.espertech.esper.example.marketdatafeed.FeedSimMain.java
public void run() { if (isWaitKeypress) { System.out.println("...press enter to start simulation..."); try {//from w ww . jav a2 s. c om System.in.read(); } catch (IOException e) { log.error("Exception reading keyboard input: " + e.getMessage(), e); } } // Configure engine with event names to make the statements more readable. // This could also be done in a configuration file. Configuration configuration = new Configuration(); configuration.addEventType("MarketDataEvent", MarketDataEvent.class.getName()); // Get engine instance EPServiceProvider epService = EPServiceProviderManager.getProvider(engineURI, configuration); // Set up statements TicksPerSecondStatement tickPerSecStmt = new TicksPerSecondStatement(epService.getEPAdministrator()); tickPerSecStmt.addListener(new RateReportingListener()); TicksFalloffStatement falloffStmt = new TicksFalloffStatement(epService.getEPAdministrator()); falloffStmt.addListener(new RateFalloffAlertListener()); // For continuous non-ending simulation if (continuousSimulation) { new MarketDataSendRunnable(epService, true).run(); } else { // Send events ExecutorService threadPool = Executors.newFixedThreadPool(numberOfThreads); MarketDataSendRunnable runnables[] = new MarketDataSendRunnable[numberOfThreads]; for (int i = 0; i < numberOfThreads; i++) { runnables[i] = new MarketDataSendRunnable(epService, false); threadPool.submit(runnables[i]); } int seconds = 0; Random random = new Random(); while (seconds < numSeconds) { seconds++; try { Thread.sleep(1000); } catch (InterruptedException e) { log.info("Interrupted", e); break; } FeedEnum feedToDropOff; if (random.nextDouble() * 100 < dropProbability) { feedToDropOff = FeedEnum.FEED_A; if (random.nextBoolean()) { feedToDropOff = FeedEnum.FEED_B; } log.info("Setting drop-off for feed " + feedToDropOff); } else { feedToDropOff = null; } for (int i = 0; i < runnables.length; i++) { runnables[i].setRateDropOffFeed(feedToDropOff); } } log.info("Shutting down threadpool"); for (int i = 0; i < runnables.length; i++) { runnables[i].setShutdown(); } threadPool.shutdown(); try { threadPool.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { // no action } } }
From source file:eu.crisis_economics.abm.firm.TestExogenousFirm.java
/** * Test whether an instance of {@link ExogenousFirm} behaves as expected. This * test operates as follows:<br><br> * //from w w w.j a va 2 s . co m * {@code (a)} * One {@link StockTradingBank} is created, to serve as a {@link StockHolder} * and {@link DepositHolder} for an {@link ExogenousFirm};<br> * {@code (b)} * One {@link ExogenousFirm} is created, as well as one goods market and one * labour market;<br> * {@code (c)} * {@link UnivariateFunction}{@code s} are created for every decision on which * the {@link ExogenousFirm} depends;<br> * {@code (d)} * One {@link ExogenousGoodsBuyer} and one {@link ExogenousEmployee} are * created. Both are connected to the relevant markets;<br> * {@code (e)} * The {@link ExogenousGoodsBuyer} is credited and debited several times, * and made subject to cash injections. It is asserted that the financial * state of the {@link DepositHolder} is unchanged;<br> * {@code (f)} * Several simulation cycles elapse. In each cycle, it is asserted that the * balance sheet of the {@link ExogenousFirm} is as expected and that the * {@link ExogenousFirm} has interacted with the markets as expected. */ @Test public void testExogenousFirmBehaviour() { final StockTradingBank bank = new StockTradingBank(1.0); // 1 to pay for initial shares final Map<String, Pair<Double, Double>> goodsTypes = // One durable good, new HashMap<String, Pair<Double, Double>>(); // one non-durable good. goodsTypes.put("type 1", Pair.create(1.0, 1.0)); // 100% time/use decay goodsTypes.put("type 2", Pair.create(0.1, 0.2)); // 10% time decay, 20% use decay. final SimpleGoodsMarket goodsMarket = new SimpleGoodsMarket(new ManualGoodsClassifier(goodsTypes), new ForagerMatchingAlgorithm(new HomogeneousRationingAlgorithm())); goodsMarket.addInstrument("type 1"); goodsMarket.addInstrument("type 2"); final SimpleLabourMarket labourMarket = new SimpleLabourMarket( new ForagerMatchingAlgorithm(new HomogeneousRationingAlgorithm())); final Random dice = new Random(1L); final class TestFunction implements UnivariateFunction { private final double grad; private TestFunction(Random dice) { grad = dice.nextDouble() + 1.; } @Override public double value(final double t) { return grad * (Math.floor(t) + 1.); } } final TimeseriesParameter<Double> deposits = createParameterFromUnivariateFunction(new TestFunction(dice)), commercialLoanDemand = createParameterFromUnivariateFunction(new TestFunction(dice)), desiredLabour = createParameterFromUnivariateFunction(new TestFunction(dice)), wageBidPrice = createParameterFromUnivariateFunction(new TestFunction(dice)), productionYield = createParameterFromUnivariateFunction(new TestFunction(dice)), sellingPrice = createParameterFromUnivariateFunction(new TestFunction(dice)), dividendPayment = createParameterFromUnivariateFunction(new TestFunction(dice)), maximumLendingRate = createParameterFromUnivariateFunction(new TestFunction(dice)); final ExogenousFirm firm = new ExogenousFirm(bank, bank, 1., // 1.0 shares emitted 1., // 1.0 per share "type 1", labourMarket, goodsMarket, deposits, commercialLoanDemand, desiredLabour, wageBidPrice, productionYield, sellingPrice, dividendPayment, maximumLendingRate, new CreditDemandFunction.RiskNeutralCreditDemandFunction(), new InstanceIDAgentNameFactory()); // Check whether debits, credits and cash flow injections are exogenous: { final double startingBankCashReserve = bank.getCashReserveValue(), startingFirmEquity = firm.getEquity(); firm.debit(Double.MAX_VALUE); firm.debit(-1.); try { firm.credit(Double.MAX_VALUE / 2.); firm.credit(-1.); } catch (InsufficientFundsException e) { Assert.fail(); } firm.cashFlowInjection(Double.MAX_VALUE / 4.); firm.cashFlowInjection(-1.); Assert.assertEquals(bank.getCashReserveValue(), startingBankCashReserve, 1.e-12); Assert.assertEquals(firm.getEquity(), startingFirmEquity, 1.e-12); } // Check whether cash allocation has memory: firm.allocateCash(100.); Assert.assertEquals(firm.getAllocatedCash(), 100., 1.e-12); firm.allocateCash(50.); Assert.assertEquals(firm.getAllocatedCash(), 150., 1.e-12); firm.disallocateCash(151.); Assert.assertEquals(firm.getAllocatedCash(), 0., 1.e-12); final ExogenousEmployee employee = new ExogenousEmployee(labourMarket); final ExogenousGoodsBuyer goodsBuyer = new ExogenousGoodsBuyer(goodsMarket); advanceTimeByOneCycle(); double productionYieldLastValue = 0.; for (int i = 0; i < 10; ++i) { employee.setLabourSupply(100., 1.); goodsBuyer.setGoodsDemand("type 1", 100.); advanceUntilJustAfterTime(NamedEventOrderings.GOODS_INPUT_MARKET_MATCHING); final double depositsValueProvided = deposits.get(), desiredLabourValueProvided = desiredLabour.get(), wageBidPriceValueProvided = wageBidPrice.get(), productionYieldValueProvided = productionYield.get(), sellingPriceValueProvided = sellingPrice.get(), dividendPaymentValueProvided = dividendPayment.get(); if (i != 0) // No trade in the first Assert.assertEquals( // simulation cycle, as goodsMarket.getInstrument("type 1") // goods are yet to .getWorstAskPriceAmongSellers(), // appear in inventory. sellingPriceValueProvided, 1.e-12); Assert.assertEquals(goodsMarket.getInstrument("type 1").getTotalSupply(), productionYieldLastValue, 1.e-12); advanceUntilJustAfterTime(NamedEventOrderings.AFTER_ALL); Assert.assertEquals(firm.getDepositValue(), depositsValueProvided, 1.e-12); Assert.assertEquals(firm.getAllocatedCash(), 0., 1.e-12); Assert.assertEquals(labourMarket.getLastLabourTotalDemand(), desiredLabourValueProvided, 1.e-12); Assert.assertEquals(firm.getCurrentDividend(), dividendPaymentValueProvided, 1.e-12); Assert.assertEquals(labourMarket.getInstrument(1).getDemandWeightedBidWage(), wageBidPriceValueProvided, 1.e-12); productionYieldLastValue = productionYieldValueProvided; } }
From source file:se.llbit.math.Ray.java
/** * Set this ray to a random diffuse reflection of the input ray. * @param ray/* w w w .j a v a2s. com*/ * @param random */ public final void diffuseReflection(Ray ray, Random random) { set(ray); // get random point on unit disk double x1 = random.nextDouble(); double x2 = random.nextDouble(); double r = FastMath.sqrt(x1); double theta = 2 * Math.PI * x2; // project to point on hemisphere in tangent space double tx = r * FastMath.cos(theta); double ty = r * FastMath.sin(theta); double tz = FastMath.sqrt(1 - x1); // transform from tangent space to world space double xx, xy, xz; double ux, uy, uz; double vx, vy, vz; if (QuickMath.abs(n.x) > .1) { xx = 0; xy = 1; xz = 0; } else { xx = 1; xy = 0; xz = 0; } ux = xy * n.z - xz * n.y; uy = xz * n.x - xx * n.z; uz = xx * n.y - xy * n.x; r = 1 / FastMath.sqrt(ux * ux + uy * uy + uz * uz); ux *= r; uy *= r; uz *= r; vx = uy * n.z - uz * n.y; vy = uz * n.x - ux * n.z; vz = ux * n.y - uy * n.x; d.x = ux * tx + vx * ty + n.x * tz; d.y = uy * tx + vy * ty + n.y * tz; d.z = uz * tx + vz * ty + n.z * tz; o.scaleAdd(Ray.OFFSET, d); currentMaterial = prevMaterial; specular = false; }
From source file:org.jtransforms.utils.IOUtils.java
/** * Fills 2D matrix with random numbers.// ww w. j a v a2 s.c o m * @param n1 rows * @param n2 columns * @param m 2D matrix */ public static void fillMatrix_2D(long n1, long n2, double[][] m) { Random r = new Random(2); for (int i = 0; i < n1; i++) { for (int j = 0; j < n2; j++) { m[i][j] = r.nextDouble(); } } }
From source file:com.twitter.graphjet.bipartite.MultiSegmentPowerLawBipartiteGraphTest.java
/** * This test is here as an example of checking for a memory leak: the idea here is to start with * a limited heap so that the JVM is forced to reclaim memory, enabling us to check that memory * from old segments is reclaimed correctly. For 18MB of heap given to the test and 1000 rounds, * we should see 10s of GC cycles, and the large number of cycles ensure that this test will fail * if there is a big memory leak. One way to check that this is working properly is to grep * the test output log like this:/*from ww w . ja v a2 s .com*/ * grep "Free memory" .pants.d/test/junit/TEST-com.twitter.graphjet.bipartite.MultiSegmentPowerLawBipartiteGraphTest.xml | sed 's/.*: //' * and then plot the data to see a oscillatory pattern that indicates memory reclaiming working * as expected. */ @Test public void testMemoryRecycling() throws Exception { int maxNumSegments = 10; int maxNumEdgesPerSegment = 8192; int leftSize = 100; int rightSize = 1000; double edgeProbability = 0.5; // this implies ~50K edges int numRounds = 1000; MultiSegmentPowerLawBipartiteGraph multiSegmentPowerLawBipartiteGraph = new MultiSegmentPowerLawBipartiteGraph( maxNumSegments, maxNumEdgesPerSegment, leftSize / 2, (int) (rightSize * edgeProbability / 2), 2.0, rightSize / 2, (int) (leftSize * edgeProbability / 2), 2.0, new IdentityEdgeTypeMask(), new NullStatsReceiver()); for (int round = 0; round < numRounds; round++) { Random random = new Random(8904572034987501L); int numSamples = 10; for (int i = 0; i < leftSize; i++) { for (int j = 0; j < rightSize; j++) { if (random.nextDouble() < edgeProbability) { multiSegmentPowerLawBipartiteGraph.addEdge(i, j, (byte) 0); } } } // on average, degree is a 500 assertEquals(511, multiSegmentPowerLawBipartiteGraph.getLeftNodeDegree(10)); Set<Long> leftNodeEdgeSet = Sets.newHashSet(multiSegmentPowerLawBipartiteGraph.getLeftNodeEdges(10)); // all edges are unique assertEquals(511, leftNodeEdgeSet.size()); List<Long> leftNodeRandomEdgeSample = Lists.newArrayList( multiSegmentPowerLawBipartiteGraph.getRandomLeftNodeEdges(10, numSamples, random)); assertEquals(numSamples, leftNodeRandomEdgeSample.size()); for (Long id : leftNodeRandomEdgeSample) { assertTrue(leftNodeEdgeSet.contains(id)); } // checking an arbitrary node System.out.println("=== Round " + round); assertTrue(multiSegmentPowerLawBipartiteGraph.getRightNodeDegree(395) > 10); Set<Long> rightNodeEdgeSet = Sets.newHashSet(multiSegmentPowerLawBipartiteGraph.getRightNodeEdges(395)); List<Long> rightNodeRandomEdgeSample = Lists.newArrayList( multiSegmentPowerLawBipartiteGraph.getRandomRightNodeEdges(395, numSamples, random)); assertEquals(numSamples, rightNodeRandomEdgeSample.size()); for (Long id : rightNodeRandomEdgeSample) { assertTrue(rightNodeEdgeSet.contains(id)); } System.out.println("Total memory available to JVM (bytes): " + Runtime.getRuntime().totalMemory()); System.out.println("Free memory (bytes): " + Runtime.getRuntime().freeMemory()); } }
From source file:br.fapesp.myutils.MyUtils.java
/** * Flip a coin using provided weights./* w w w . j a v a2s . c om*/ * @param probTrue the probability the event is true * @param rng * @param seed * @return */ public static boolean weightedCoinFlip(double probTrue, Random rng, long seed) { Random r; double flip; if (rng == null) r = new Random(seed); else r = rng; flip = r.nextDouble(); if (flip <= probTrue) return true; else return false; }
From source file:com.duy.pascal.interperter.libraries.math.MathLib.java
@PascalMethod(description = "") public long RandomRange(long from, long to) { Random r = new Random(); return from + ((long) (r.nextDouble() * (to - from))); }
From source file:org.apache.accumulo.test.randomwalk.conditional.Transfer.java
@Override public void visit(State state, Environment env, Properties props) throws Exception { String table = state.getString("tableName"); Random rand = (Random) state.get("rand"); Connector conn = env.getConnector(); int numAccts = (Integer) state.get("numAccts"); // note: non integer exponents are slow ZipfDistributionImpl zdiBanks = new ZipfDistributionImpl((Integer) state.get("numBanks"), 1); String bank = Utils.getBank(zdiBanks.inverseCumulativeProbability(rand.nextDouble())); ZipfDistributionImpl zdiAccts = new ZipfDistributionImpl(numAccts, 1); String acct1 = Utils.getAccount(zdiAccts.inverseCumulativeProbability(rand.nextDouble())); String acct2 = Utils.getAccount(zdiAccts.inverseCumulativeProbability(rand.nextDouble())); while (acct2.equals(acct1)) { // intentionally not using zipf distribution to pick on retry acct2 = Utils.getAccount(rand.nextInt(numAccts)); }//from www. j a v a 2s . com // TODO document how data should be read when using ConditionalWriter Scanner scanner = new IsolatedScanner(conn.createScanner(table, Authorizations.EMPTY)); scanner.setRange(new Range(bank)); scanner.fetchColumnFamily(new Text(acct1)); scanner.fetchColumnFamily(new Text(acct2)); Account a1 = new Account(); Account a2 = new Account(); Account a; for (Entry<Key, Value> entry : scanner) { String cf = entry.getKey().getColumnFamilyData().toString(); String cq = entry.getKey().getColumnQualifierData().toString(); if (cf.equals(acct1)) a = a1; else if (cf.equals(acct2)) a = a2; else throw new Exception("Unexpected column fam: " + cf); if (cq.equals("bal")) a.setBal(entry.getValue().toString()); else if (cq.equals("seq")) a.setSeq(entry.getValue().toString()); else throw new Exception("Unexpected column qual: " + cq); } int amt = rand.nextInt(50); log.debug("transfer req " + bank + " " + amt + " " + acct1 + " " + a1 + " " + acct2 + " " + a2); if (a1.bal >= amt) { ConditionalMutation cm = new ConditionalMutation(bank, new Condition(acct1, "seq").setValue(Utils.getSeq(a1.seq)), new Condition(acct2, "seq").setValue(Utils.getSeq(a2.seq))); cm.put(acct1, "bal", (a1.bal - amt) + ""); cm.put(acct2, "bal", (a2.bal + amt) + ""); cm.put(acct1, "seq", Utils.getSeq(a1.seq + 1)); cm.put(acct2, "seq", Utils.getSeq(a2.seq + 1)); ConditionalWriter cw = (ConditionalWriter) state.get("cw"); Status status = cw.write(cm).getStatus(); while (status == Status.UNKNOWN) { log.debug("retrying transfer " + status); status = cw.write(cm).getStatus(); } log.debug("transfer result " + bank + " " + status + " " + a1 + " " + a2); } }