Example usage for java.util Random nextDouble

List of usage examples for java.util Random nextDouble

Introduction

In this page you can find the example usage for java.util Random nextDouble.

Prototype

public double nextDouble() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.

Usage

From source file:com.authorwjf.bounce.BluetoothChat.java

private void fetchScoreboardFunc() {
    // Fetch the scores ...
    AsyncTask.execute(new Runnable() {
        public void run() {
            try {
                // Instantiate the scoreboardEntriesList
                //ArrayList<ScoreboardEntry> scoreboardEntriesList = new ArrayList<ScoreboardEntry>();

                // Get the attributes used for the HTTP GET
                //String currentUserFBID = application.getCurrentFBUser().getId();
                //String currentUserAccessToken = Session.getActiveSession().getAccessToken();
                Random rgen = new Random();
                double currentScore = rgen.nextDouble();
                String currentUserFBID = Main.fbid;
                // Execute the HTTP Get to our server for the scores of the user's friends
                HttpClient client = new DefaultHttpClient();
                /* Update this */
                //String getURL = "http://www.friendsmash.com/scores?fbid=" + currentUserFBID + "&access_token=" + currentUserAccessToken;
                String getURL = "http://omnidrive.herokuapp.com/data?fbid=" + currentUserFBID + "&currentScore="
                        + currentScore;//  www.j a  va  2 s  .  c o  m
                //String getURL = "http://www.omnidrive.io/api/?fbid=" + currentUserFBID + "&currentScore=" + mpg;
                HttpGet get = new HttpGet(getURL);
                HttpResponse responseGet = client.execute(get);

            } catch (Exception e) {
                Log.e(BluetoothChat.TAG, e.toString());
            }
        }

    });
}

From source file:common.matrix.GaussianProbaTest.java

@Test
public void Gaussian1D() {
    final Graph graph = new GraphBuilder().withPlugin(new MLXPlugin()).withScheduler(new NoopScheduler())
            .build();//from w  w  w .  j  a  va  2 s .  c  om
    graph.connect(new Callback<Boolean>() {
        @Override
        public void on(Boolean result) {
            final GaussianMixtureNode gaussianNode = (GaussianMixtureNode) graph.newTypedNode(0, 0,
                    GaussianMixtureNode.NAME);
            final double eps = 1e-7;

            final int total = 16;
            final double[][] train = new double[total][1];
            final Random rand = new Random();

            double sum = 0;
            double sumsquare = 0;
            for (int i = 0; i < 16; i++) {
                train[i][0] = rand.nextDouble() * 100;
                sum += train[i][0];
                sumsquare += train[i][0] * train[i][0];

                final int finalI = i;
                gaussianNode.jump(i, new Callback<Node>() {
                    @Override
                    public void on(Node result) {
                        gaussianNode.learnVector(train[finalI], new Callback<Boolean>() {
                            @Override
                            public void on(Boolean result) {

                            }
                        });
                        result.free();
                    }
                });

            }

            final double finalSum = sum;
            final double finalSumsquare = sumsquare;
            gaussianNode.jump(16, new Callback<GaussianMixtureNode>() {
                @Override
                public void on(GaussianMixtureNode result) {
                    double[] avgBatch = result.getAvg();
                    Matrix covBatch = result.getCovariance(avgBatch, null);

                    //System.out.println("Avg: " + avgBatch[0] + " " + sum / total);
                    //System.out.println("Var: " + covBatch[0][0] + " " + Gaussian1D.getCovariance(sum, sumsquare, total));
                    Assert.assertTrue(Math.abs(avgBatch[0] - finalSum / total) < eps);
                    Assert.assertTrue(Math.abs(covBatch.get(0, 0)
                            - Gaussian1D.getCovariance(finalSum, finalSumsquare, total)) < eps);

                    double testvec = rand.nextDouble() * 100;
                    System.out
                            .println("Prob: " + Gaussian1D.getDensity(finalSum, finalSumsquare, total, testvec)
                                    + " " + result.getProbability(new double[] { testvec }, null, false));
                    Assert.assertTrue(Math.abs(Gaussian1D.getDensity(finalSum, finalSumsquare, total, testvec)
                            - result.getProbability(new double[] { testvec }, null, false)) < eps);

                }
            });

        }
    });

}

From source file:org.alfresco.textgen.TextGenerator.java

public String generateQueryString(long seed, int words, int wordLimit) {
    if (wordLimit < words) {
        throw new IllegalStateException();
    }//ww w  .ja va 2  s .c o m

    Random random = new Random();
    random.setSeed(seed);

    int start = 0;
    if (wordLimit > words) {
        start = random.nextInt(wordLimit - words);
    }

    random.setSeed(seed);

    for (int i = 0; i < start; i++) {
        random.nextDouble();
    }

    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < words; i++) {
        String word = wordGenerator.getWord(random.nextDouble());
        if (buffer.length() > 0) {
            buffer.append(" ");
        }
        buffer.append(word);
    }
    return buffer.toString();
}

From source file:eionet.gdem.utils.FileUpload.java

/**
 * Returns unique number, used for temporary file name.
 *///  ww w .  j av a  2 s.  co  m
private String getSessionId() {
    String s = "";
    synchronized (SessionIdLock) {
        long l = System.currentTimeMillis();
        Random random = new Random();
        s = String.valueOf(l);
        for (int i = 1; i <= HOW_LONG; i++) {
            s = s + (int) (1.0D + HOW_LONG * random.nextDouble());
        }
    }
    return s;
}

From source file:org.jtransforms.utils.IOUtils.java

/**
 * Fills 1D matrix with random numbers./*from w  w w  . j av a2s .  c  om*/
* @param N  size
* @param m  1D matrix
*/
public static void fillMatrix_1D(long N, double[] m) {
    Random r = new Random(2);
    for (int i = 0; i < N; i++) {
        m[i] = r.nextDouble();
    }
}

From source file:com.tengel.time.MobControl.java

public void onCreatureSpawn(CreatureSpawnEvent event) {
    LivingEntity creature = event.getEntity();
    if (creature instanceof Monster) {
        Location loc = event.getLocation();
        World w = loc.getWorld();//w w  w .  ja v  a  2s  . co m
        SpawnReason sr = event.getSpawnReason();
        if (w.getName().equalsIgnoreCase("Time")) {
            if ((sr == SpawnReason.NATURAL) || (sr == SpawnReason.DEFAULT)) {
                event.setCancelled(true);
                return;
            }
            if (sr == SpawnReason.CUSTOM) {
                if (!playerInChunkRadius(loc, 5)) {
                    String region = "";
                    RegionManager mgr = plugin.worldGuard.getRegionManager(w);
                    for (ProtectedRegion rg : mgr.getApplicableRegions(loc)) {
                        if (rg.getId().contains("spawn_"))
                            region = rg.getId();
                    }
                    int zone = plugin.getRegionControl().getZoneId(loc);
                    int difficulty = getSpawnDifficulty(region);
                    Random r_gen = new Random();
                    double multiplier = 1.2 - r_gen.nextDouble() * 0.4;
                    int level = (int) (zone * 66 + ((difficulty - 1) * 13) + 7 - 6
                            + Math.round(r_gen.nextDouble() * 12));
                    setArmours(creature, zone, difficulty);
                    setHealth(creature, level, multiplier);
                    setName(creature, level, multiplier);

                    PotionEffect pe = new PotionEffect(PotionEffectType.SPEED, 3000, zone);
                    creature.addPotionEffect(pe);

                    creature.setCustomNameVisible(true);
                    creature.setRemoveWhenFarAway(false);
                    creature.setCanPickupItems(false);
                    return;
                } else {
                    plugin.getMobControl().removeTimeMonster(creature.getUniqueId());
                    plugin.getServer().getScheduler().runTaskLater(plugin,
                            new TimeMonsterSpawn(plugin, event.getLocation(), creature.getType().name()),
                            20 * 10);
                    event.setCancelled(true);
                    return;
                }
            }
        }
    }
}

From source file:org.signserver.test.random.cli.Main.java

/**
 * Creates two groups of threads, one performing signings and the other 
 * renewing the signers./*from   ww  w .  j  a  v  a  2s.c  om*/
 * 
 * There can be any number of workers and threads in group 1 performing signings.
 * 
 * Group 2 is the workers that will be renewed by the renewalworker in group 3.
 * 
 * The goals with the test are:
 * a) Test that it is possible to sign at the same time as the signers are renewed.
 *
 * - Notice that for instance a FirstActiveDispatcher might have to be used 
 *   in order to be able to sign while some of the workers are being renewed
 *   as there is a time for which the worker will be offline during renewal.
 */
private static void signWhileRenewing(final List<WorkerThread> threads, final TestContext context)
        throws Exception {

    if (context.getThreadsGroup1() == null) {
        throw new ParseException("Missing -threadgroup1");
    }

    if (context.getWorkerGroup3() == null) {
        throw new ParseException("Missing -workergroup3");
    }

    if (context.getWorkerGroup3().size() != 1) {
        throw new ParseException("Only one (renewal) worker allowed (worker group 3)");
    }

    if (!context.getWorkerGroup3().get(0).getWorkerType().equals(WorkerType.renew)) {
        throw new ParseException("The worker in group 3 must be of type " + WorkerType.renew + ".");
    }

    // Group 1: Threads signing documents with the workers in group 1
    for (int i = 0; i < context.getThreadsGroup1(); i++) {
        final WorkerSpec worker = context.getWorkerGroup1().get(i % context.getWorkerGroup1().size());
        final SigningThread signingThread = new SigningThread("Signer-" + i + "-" + worker.getWorkerId(),
                context.getCallback(), null, context.getMasterRandom().nextLong(), worker,
                context.getWorkerSession(), null);
        threads.add(signingThread);
    }

    // Group 3: Threads updating the configuration of the workers in group 2
    final int workerId = context.getWorkerGroup3().get(0).getWorkerId();
    final List<WorkerSpec> renewees = context.getWorkerGroup2();
    final List<RenewSigner> renewers = new LinkedList<RenewSigner>();
    for (WorkerSpec renewee : renewees) {
        renewers.add(new RenewSigner(workerId, renewee.getWorkerId(), context.getWorkerSession()));
    }

    final long seed = context.getMasterRandom().nextLong();
    final WorkerThread renewals = new WorkerThread("Renewal-" + workerId, context.getCallback()) {

        @Override
        public void run() {
            final Pauser pauser = context.getPauser();
            final Random random = new Random(seed);
            try {
                while (!isStop()) {
                    for (final RenewSigner renewer : renewers) {
                        if (pauser != null) {
                            pauser.pause();
                        }
                        try {
                            renewer.run();
                        } catch (FailedException ex) {
                            fireFailure("WORKER" + workerId + " renewing of " + renewer.getReneweeId()
                                    + " failed after " + getOperationsPerformed() + " signings: "
                                    + ex.getMessage());
                            break;
                        }
                        // Sleep
                        Thread.sleep((int) (random.nextDouble() * 500.0));
                        increaseOperationsPerformed();
                    }
                }
            } catch (InterruptedException ex) {
                LOG.error("Interrupted: " + ex.getMessage());
            }
        }

    };
    threads.add(renewals);
}

From source file:com.adwhirl.AdWhirlManager.java

public Ration getRation() {
    Random random = new Random();

    double r = random.nextDouble() * totalWeight;
    double s = 0;

    Log.d(AdWhirlUtil.ADWHIRL, "Dart is <" + r + "> of <" + totalWeight + ">");

    Iterator<Ration> it = this.rationsList.iterator();
    Ration ration = null;/*from   w w  w. j av  a2s.  c  o  m*/
    while (it.hasNext()) {
        ration = it.next();
        s += ration.weight;

        if (s >= r) {
            break;
        }
    }

    return ration;
}

From source file:org.jtransforms.utils.IOUtils.java

/**
 * Fills 1D matrix with random numbers./* ww  w. j a va 2  s  . c  o  m*/
* @param N  size
* @param m  1D matrix
*/
public static void fillMatrix_1D(long N, DoubleLargeArray m) {
    Random r = new Random(2);
    for (long i = 0; i < N; i++) {
        m.setDouble(i, r.nextDouble());
    }
}

From source file:com.sumit.test.client.KeyValueClientThread.java

public KeyValueClientThread(IKVService<T> _client, GlobalConfig config, long _insertStart, long _insertEnd,
        IValueFactory<T> _valueFactory, QueryRepo<? extends Query<T>, T> _queryRepo) {
    this.client = _client;
    this.valueFactory = _valueFactory;
    this.operationCount = config.getOperationCount();
    this.insertStart = _insertStart;
    this.insertEnd = _insertEnd;

    this.queryRepo = _queryRepo;
    this.queryIndex = config.getQueryIndex();
    this.pageSize = config.getPageSize();

    OperationType operationType = config.getOperationType();
    opRespTimesMap.put(operationType, new ArrayList<>());
    switch (operationType) {
    case INSERT: {
        func = new Func() {
            public void run() {
                List<Long> respTimes = opRespTimesMap.get(OperationType.INSERT);
                for (long i = insertStart; i < insertEnd; i++) {
                    long time = System.currentTimeMillis();
                    client.insert(String.valueOf(i), valueFactory.create(i));
                    respTimes.add(System.currentTimeMillis() - time);
                }/*from w w  w  .ja v  a  2 s.  c  o m*/
            }
        };
        break;
    }
    case READ: {
        func = new Func() {
            public void run() {
                List<Long> respTimes = opRespTimesMap.get(OperationType.READ);
                for (int i = 0; i < operationCount; i++) {
                    long time = System.currentTimeMillis();
                    T val = client.get(genRandomKey());
                    respTimes.add(System.currentTimeMillis() - time);
                }
            }
        };
        break;
    }
    case UPDATE: {
        func = new Func() {
            public void run() {
                List<Long> respTimes = opRespTimesMap.get(OperationType.UPDATE);
                for (long i = 0; i < operationCount; i++) {
                    long time = System.currentTimeMillis();
                    client.update(genRandomKey(), valueFactory.create(i));
                    respTimes.add(System.currentTimeMillis() - time);
                }
            }
        };
        break;
    }
    case N1QL: {
        func = new Func() {
            public void run() throws JsonProcessingException {
                List<Long> respTimes = opRespTimesMap.get(OperationType.N1QL);
                Random randomKey = new Random();
                List<? extends Query<T>> queries = queryRepo.getQueries();
                for (long i = -20; i < operationCount; i++) {
                    int currQueryIndex = queryIndex != -1 ? queryIndex
                            : (int) (randomKey.nextDouble() * queries.size());
                    Query<T> query = queries.get(currQueryIndex);
                    T params = queryRepo.getRandomParams();
                    long time = System.currentTimeMillis();
                    client.executeQuery(query, params, pageSize);
                    if (i > 0) {
                        System.out.println("Query: " + i);
                        respTimes.add(System.currentTimeMillis() - time);
                    }
                }
            }
        };
        break;
    }
    default: {
        throw new UnsupportedOperationException(operationType.toString());
    }
    }
}