Example usage for java.lang Math random

List of usage examples for java.lang Math random

Introduction

In this page you can find the example usage for java.lang Math random.

Prototype

public static double random() 

Source Link

Document

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0 .

Usage

From source file:junglespeed.service.ConfigService.java

public void distributionCartes(Partie partie) {

    map.put(1, "BLUE");
    map.put(2, "RED");
    map.put(3, "YELLOW");
    map.put(4, "GREEN");
    map.put(5, "GREY");
    map.put(6, "WHITE");
    map.put(7, "BLACK");
    map.put(8, "BLUE");

    int lower = 1;
    int higher = 8;

    for (Joueur joueur : partie.getJoueurs()) {
        for (int i = 0; i < nbCartes; i++) {
            int random = (int) (Math.random() * (higher - lower + 1)) + lower;
            Carte carte = new Carte(map.get(random), joueur);
            joueur.getCartes().add(carte);
            carteService.save(carte);//  ww  w  .j a v  a  2  s  .  co  m
            joueurService.save(joueur);
        }
    }
}

From source file:edu.umass.cs.protocoltask.examples.pingpong.PingPongProtocolTask.java

@Override
public String refreshKey() {
    return (this.key = (this.myID.toString() + (int) (Math.random() * Integer.MAX_VALUE)));
}

From source file:edu.ucsf.valelab.saim.calculations.TestSaimFitter.java

public void test() throws Exception {
    double wavelength = 488.0;
    double nSample = 1.36;
    double dOx = 500.0;

    double A = 100.0;
    double B = 100.0;
    double h = 16.0;

    double fractionMaxError = 0.0000001;
    final int nrTries = 10;

    // make a collection of "observed" points
    ArrayList<WeightedObservedPoint> points = new ArrayList<WeightedObservedPoint>();
    for (int i = -50; i <= 50; i += 2) {
        double angle = Math.toRadians(i);
        double I = A * SaimCalc.fieldStrength(wavelength, angle, nSample, dOx, h) + B;
        WeightedObservedPoint point = new WeightedObservedPoint(1.0, angle, I);
        points.add(point);/*from   w  w  w  . java  2 s.  c  o m*/
    }

    // create the fitter
    SaimFunctionFitter sff = new SaimFunctionFitter(wavelength, dOx, nSample, false);
    double[] values = new double[] { A, B, h };

    // test by varying the input for height
    for (int i = 0; i < nrTries; i++) {
        double[] guess = values.clone();
        guess[0] = 50.0;
        guess[1] = 150.0;
        guess[2] = guess[2] + (guess[2] * (Math.random() - 0.5) * 10);
        if (guess[2] < 1.0)
            guess[2] = 1.0;
        for (int j = 0; j < guess.length; j++) {
            System.out.println("Guess: " + j + " " + guess[j]);
        }

        sff.setGuess(guess);

        final double[] coefficients = sff.fit(points);
        for (int j = 0; j < coefficients.length; j++) {
            System.out
                    .println("coefficient " + j + ", expected:  " + values[j] + ", found: " + coefficients[j]);
            assertEquals(values[j], coefficients[j], values[j] * fractionMaxError);
        }

        System.out.println("Value was calculated: " + sff.getCalcCount() + " times");
        sff.resetCalcCount();
    }

    // test by adding noise to the input
    // make a collection of "observed" points
    final double noiseFactor = 0.1; // 10% noise
    fractionMaxError = noiseFactor;

    double[] guess = values.clone();
    guess[0] = 50.0;
    guess[1] = 150.0;
    guess[2] = 50.0;
    for (int j = 0; j < guess.length; j++) {
        System.out.println("Guess: " + j + " " + guess[j]);
    }

    for (int i = 0; i < nrTries; i++) {
        ArrayList<WeightedObservedPoint> noisyPoints = new ArrayList<WeightedObservedPoint>();
        for (int j = -50; j <= 50; j += 2) {
            double angle = Math.toRadians(j);
            double I = A * SaimCalc.fieldStrength(wavelength, angle, nSample, dOx, h) + B;
            WeightedObservedPoint noisyPoint = new WeightedObservedPoint(1.0, angle,
                    I + I * (Math.random() - 0.5) * noiseFactor);
            noisyPoints.add(noisyPoint);
        }

        sff.setGuess(guess);

        final double[] coefficients = sff.fit(noisyPoints);
        for (int j = 0; j < coefficients.length; j++) {
            System.out
                    .println("coefficient " + j + ", expected:  " + values[j] + ", found: " + coefficients[j]);
            assertEquals(values[j], coefficients[j], values[j] * fractionMaxError);
        }

        System.out.println("Value was calculated: " + sff.getCalcCount() + " times");
        sff.resetCalcCount();
    }

}

From source file:com.mpush.test.client.ConnClientTestMain.java

private static void testConnClient(int count, String userPrefix, int printDelay, boolean sync)
        throws Exception {
    Logs.init();/*from w  w w  .j  a  v a 2s  . co  m*/
    ConnClientBoot boot = new ConnClientBoot();
    boot.start().get();

    List<ServiceNode> serverList = boot.getServers();
    if (serverList.isEmpty()) {
        boot.stop();
        System.out.println("no mpush server.");
        return;
    }

    if (printDelay > 0) {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
                () -> System.err.println(ConnClientChannelHandler.STATISTICS), 3, printDelay, TimeUnit.SECONDS);
    }

    for (int i = 0; i < count; i++) {
        String clientVersion = "1.0." + i;
        String osName = "android";
        String osVersion = "1.0.1";
        String userId = userPrefix + "user-" + i;
        String deviceId = userPrefix + "test-device-id-" + i;
        byte[] clientKey = CipherBox.I.randomAESKey();
        byte[] iv = CipherBox.I.randomAESIV();

        ClientConfig config = new ClientConfig();
        config.setClientKey(clientKey);
        config.setIv(iv);
        config.setClientVersion(clientVersion);
        config.setDeviceId(deviceId);
        config.setOsName(osName);
        config.setOsVersion(osVersion);
        config.setUserId(userId);

        int L = serverList.size();
        int index = (int) ((Math.random() % L) * L);
        ServiceNode node = serverList.get(index);

        ChannelFuture future = boot.connect(node.getAttr(ATTR_PUBLIC_IP), node.getPort(), config);
        if (sync)
            future.awaitUninterruptibly();
    }
}

From source file:baggage.BaseTestCase.java

protected long randomLong() {
    return (long) (Math.random() * 100000d);
}

From source file:net.sf.ipsedixit.core.impl.DefaultDataProvider.java

/**
 * {@inheritDoc}/*from w w w  .  jav a 2s  .co  m*/
 */
public double randomDoubleInRange(double minInclusive, double maxExclusive) {
    return (Math.random() * (maxExclusive - minInclusive)) + minInclusive;
}

From source file:edu.ucsf.valelab.saim.calculations.TestSaimErrorFunctionFitter.java

public void test() throws Exception {
    SaimData data = new SaimData();

    data.wavelength_ = 488.0;/* w w w . ja  va 2  s . com*/
    data.nSample_ = 1.36;
    data.dOx_ = 500.0;
    data.A_ = 1000.0;
    data.B_ = 5000.0;
    data.heights_ = new double[] { 75.0 };

    double maxError = 0.00000000001;
    int nrRepeats = 5;

    // make a collection of "observed" points
    ArrayList<WeightedObservedPoint> points = new ArrayList<WeightedObservedPoint>();
    for (int i = -50; i <= 50; i += 1) {
        double angle = Math.toRadians(i);
        double I = data.A_
                * SaimCalc.fieldStrength(data.wavelength_, angle, data.nSample_, data.dOx_, data.heights_[0])
                + data.B_;
        WeightedObservedPoint point = new WeightedObservedPoint(1.0, angle, I);
        points.add(point);
    }
    System.out.println("BOBYQA Test results (TestSaimErrorFunctionFitter:");
    System.out.println("Goal: " + data.A_ + ", " + data.B_ + ", " + data.heights_[0]);

    for (int i = 0; i < nrRepeats; i++) {
        SaimErrorFunctionFitter sef = new SaimErrorFunctionFitter(data);
        double[] guess = { Math.random() * 4000.0, Math.random() * 10000.0, Math.random() * 300.0 };
        sef.setGuess(guess);
        double[] result = sef.fit(points);
        System.out.println("Guess: " + guess[0] + ", " + guess[1] + ", " + guess[2]);
        System.out.println("Result: " + result[0] + ", " + result[1] + ", " + result[2]);

    }
}

From source file:Retailer.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    try {/*w  ww. j  a v a  2s. c  o m*/
        Connection connection = connectionFactory.createConnection();

        // The Retailer's session is non-trasacted.
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination vendorOrderQueue = session.createQueue("VendorOrderQueue");
        TemporaryQueue retailerConfirmQueue = session.createTemporaryQueue();

        MessageProducer producer = session.createProducer(vendorOrderQueue);
        MessageConsumer replyConsumer = session.createConsumer(retailerConfirmQueue);

        connection.start();

        for (int i = 0; i < 5; i++) {
            MapMessage message = session.createMapMessage();
            message.setString("Item", "Computer(s)");
            int quantity = (int) (Math.random() * 4) + 1;
            message.setInt("Quantity", quantity);
            message.setJMSReplyTo(retailerConfirmQueue);
            producer.send(message);
            System.out.println("Retailer: Ordered " + quantity + " computers.");

            MapMessage reply = (MapMessage) replyConsumer.receive();
            if (reply.getBoolean("OrderAccepted")) {
                System.out.println("Retailer: Order Filled");
            } else {
                System.out.println("Retailer: Order Not Filled");
            }
        }

        // Send a non-MapMessage to signal the end
        producer.send(session.createMessage());

        replyConsumer.close();
        connection.close();

    } catch (JMSException e) {
        e.printStackTrace();
    }
}

From source file:org.smigo.user.UserHandler.java

public User createUser() {
    for (int tries = 0; tries < 5; tries++) {
        String username = "user" + (int) (Math.random() * 1000000);
        final List<User> users = userDao.getUsersByUsername(username);
        if (users.size() == 0) {
            final Locale locale = getLocale();
            return createUser(username, null, locale, false);
        }//w w  w.  j a va  2 s.  co m
    }
    throw new IllegalStateException("Tried 5 times and could not find a free username");
}

From source file:SortItem.java

/**
 * Fill the array with random numbers from 0..n-1.
 *///from   ww w.j  av a2 s  .  c o  m
void scramble() {
    int[] a = new int[size().height / 2];
    double f = size().width / (double) a.length;
    for (int i = a.length; --i >= 0;) {
        a[i] = (int) (i * f);
    }
    for (int i = a.length; --i >= 0;) {
        int j = (int) (i * Math.random());
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
    arr = a;
}