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.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java

/**
 * NOTE: This is a copy of TestUtils.generateTestMatrix, it was replicated in order to prevent
 * dependency of SystemML.jar to our test package.
 */// w w  w  . ja va 2 s  .c  o m
public static double[][] generateTestMatrix(int rows, int cols, double min, double max, double sparsity,
        long seed) {
    double[][] matrix = new double[rows][cols];
    Random random;
    if (seed == -1)
        random = new Random(System.nanoTime());
    else
        random = new Random(seed);

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (random.nextDouble() > sparsity)
                continue;
            matrix[i][j] = (random.nextDouble() * (max - min) + min);
        }
    }

    return matrix;
}

From source file:common.matrix.GaussianProbaTest.java

@Test
public void Singularity() {
    final Graph graph = new GraphBuilder().withPlugin(new MLXPlugin()).withScheduler(new NoopScheduler())
            .build();/* w w  w .j a v  a  2  s  . co  m*/
    graph.connect(new Callback<Boolean>() {
        @Override
        public void on(Boolean result) {
            double[] data = new double[3];
            double[] datan = new double[4];

            Random rand = new Random();

            GaussianMixtureNode node1 = (GaussianMixtureNode) graph.newTypedNode(0, 0,
                    GaussianMixtureNode.NAME);
            GaussianMixtureNode node2 = (GaussianMixtureNode) graph.newTypedNode(0, 0,
                    GaussianMixtureNode.NAME);

            node1.set(GaussianMixtureNode.FROM, "f1;f2;f3");
            node2.set(GaussianMixtureNode.FROM, "f1;f2;f3;f4");

            for (int i = 0; i < 1000; i++) {
                data[0] = 8 + rand.nextDouble() * 4; //avg =10, [8,12]
                data[1] = 90 + rand.nextDouble() * 20; //avg=100 [90,110]
                data[2] = -60 + rand.nextDouble() * 20; //avg=-50 [-60,-40]

                datan[0] = data[0];
                datan[1] = data[1];
                datan[2] = data[2];
                datan[3] = 0 * data[0] + 0 * data[1] + 0 * data[2];

                node1.set("f1", data[0]);
                node1.set("f2", data[1]);
                node1.set("f3", data[2]);

                node2.set("f1", datan[0]);
                node2.set("f2", datan[1]);
                node2.set("f3", datan[2]);
                node2.set("f4", datan[3]);

                node1.learn(new Callback<Boolean>() {
                    @Override
                    public void on(Boolean result) {

                    }
                });

                node2.learn(new Callback<Boolean>() {
                    @Override
                    public void on(Boolean result) {

                    }
                });
            }

            double[] avg = node1.getAvg();
            double[] avg2 = node2.getAvg();

            //printd(avg);
            //printd(avg2);

            data[0] = 10;
            data[1] = 100;
            data[2] = -60;

            datan[0] = data[0];
            datan[1] = data[1];
            datan[2] = data[2];
            datan[3] = 0 * data[0] + 0 * data[1] + 0 * data[2];

            double p = node1.getProbability(avg, null, false);
            double p2 = node2.getProbability(avg2, null, false);
            Assert.assertTrue(Math.abs(p - p2) < 1e-5);
            //System.out.println("p1: " + p);
            // System.out.println("p2: " + p2);

        }

        private void printd(double[] avg) {
            for (double d : avg) {
                System.out.print(d + " ");
            }
            System.out.println();

        }
    });
}

From source file:org.unitime.timetable.test.StudentSectioningTest.java

private static HashSet generateAvailableChoices(Offering offering, Random rnd, double availProb) {
    HashSet ret = new HashSet();
    for (Iterator e = offering.getConfigs().iterator(); e.hasNext();) {
        Config config = (Config) e.next();
        HashSet touchedSubparts = new HashSet();
        Vector subparts = new Vector(config.getSubparts());
        for (int i = subparts.size() - 1; i >= 0; i--) {
            Subpart subpart = (Subpart) subparts.elementAt(i);
            if (touchedSubparts.add(subpart)) {
                boolean added = false;
                for (Iterator f = subpart.getChoices().iterator(); f.hasNext();) {
                    Choice choice = (Choice) f.next();
                    if (rnd.nextDouble() < availProb) {
                        Vector sections = new Vector(choice.getSections());
                        Section section = (Section) sections
                                .elementAt((int) rnd.nextDouble() * sections.size());
                        while (section != null) {
                            added = true;
                            ret.add(section.getChoice());
                            touchedSubparts.add(section.getSubpart());
                            section = section.getParent();
                        }/*from   ww  w.  j  a v  a 2 s .c o  m*/
                    }
                }
                if (!added && subpart.getSections().size() > 0) {
                    Section section = (Section) subpart.getSections()
                            .get((int) rnd.nextDouble() * subpart.getSections().size());
                    while (section != null) {
                        ret.add(section.getChoice());
                        touchedSubparts.add(section.getSubpart());
                        section = section.getParent();
                    }
                }
            }
        }
    }
    return ret;
}

From source file:org.broadinstitute.gatk.utils.UtilsUnitTest.java

@Test(dataProvider = "asDoubleListData")
public void testAsDoubleList(final double[] values) {
    if (values == null) {
        try {/* w w w  . ja  va 2  s  .  c o m*/
            Utils.asList((int[]) null);
            Assert.fail("Should have thrown an exception");
        } catch (final IllegalArgumentException ex) {
            // good.
        }
    } else {
        final Random rdn = Utils.getRandomGenerator();
        final double[] valuesClone = values.clone();
        final List<Double> list = Utils.asList(valuesClone);
        Assert.assertNotNull(list);
        Assert.assertEquals(list.size(), values.length);
        for (int i = 0; i < values.length; i++)
            Assert.assertEquals((double) list.get(i), values[i]);
        for (int i = 0; i < values.length; i++)
            valuesClone[rdn.nextInt(values.length)] = rdn.nextDouble() * 1000;
        for (int i = 0; i < values.length; i++)
            Assert.assertEquals((double) list.get(i), valuesClone[i]);
    }
}

From source file:de.cebitec.readXplorer.differentialExpression.plot.ExpressTestGraphicsTopComponent.java

public Map<PersistentFeature, Pair<Double, Double>> createSamplePoints(int n) {
    Random r = new Random(System.nanoTime());
    Map<PersistentFeature, Pair<Double, Double>> points = new HashMap<>();
    for (int i = 0; i < n; i++) {
        PersistentFeature dummyFeature = new PersistentFeature(0, 0, "", "", "", "", 0, 0, true,
                FeatureType.ANY, "");
        double random = Math.random();
        if (random > 0.95) {
            points.put(dummyFeature, new Pair<>(r.nextDouble() * 256.0d, Double.POSITIVE_INFINITY));
            points.put(dummyFeature, new Pair<>(r.nextDouble() * 256.0d, Double.NEGATIVE_INFINITY));
        } else {/*  ww  w.j  a  v  a  2  s.c om*/
            points.put(dummyFeature, new Pair<>(2 * i + (r.nextGaussian() - 0.5d), r.nextDouble() * 256.0d));
        }
    }
    PersistentFeature dummyFeature = new PersistentFeature(0, 0, "", "", "", "", 0, 0, true, FeatureType.ANY,
            "");
    points.put(dummyFeature, new Pair<>(200d, 300d));
    dummyFeature = new PersistentFeature(0, 0, "", "", "", "", 0, 0, true, FeatureType.ANY, "");
    points.put(dummyFeature, new Pair<>(100d, Double.POSITIVE_INFINITY));
    return points;
}

From source file:com.conwet.silbops.model.JSONvsRMIPerfT.java

@Test
public void testAdvSubscription() {

    Advertise subscription = new Advertise();
    subscription.attribute("Test1", Type.DOUBLE);
    subscription.attribute("Test2", Type.STRING);

    Random random = new Random();
    Advertise[] subscriptions = new Advertise[1000 * 10];
    for (int i = 0; i < subscriptions.length; i++) {
        subscriptions[i] = new Advertise();
        subscriptions[i].attribute(new Double(random.nextDouble()).toString().substring(0, 6), Type.DOUBLE);
        subscriptions[i].attribute(new Double(random.nextDouble()).toString().substring(0, 6), Type.STRING);
    }/*from  w ww  .ja  v  a2 s .c o m*/

    System.out.println("*****************TESTING ADVFILTERS*****************");

    //Externalize and desexternalize one
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    externalizeObject(subscription, baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    desexternalizeObjects(bais, 1);

    //Externalize and desexternalize several
    baos = new ByteArrayOutputStream();
    externalizeSeveralObjects(subscriptions, baos);
    bais = new ByteArrayInputStream(baos.toByteArray());
    desexternalizeObjects(bais, subscriptions.length);

    //Size Externalize with types
    sizeExternalizeWithTypes(MessageType.ADVERTISE.name(), subscription);
    sizeExternalizeSeveralWithType(MessageType.ADVERTISE.name(), subscriptions);

    //Size Externalize without types
    sizeExternalizeWithoutTypes(subscription);
    sizeExternalizeSeveralWithoutTypes(subscriptions);

    //JSONize and desJSONize one object
    baos = new ByteArrayOutputStream();
    jSONizeObject(subscription, baos);
    bais = new ByteArrayInputStream(baos.toByteArray());
    desJSONizeAdvs(bais, 1);

    //JSONize and desJSONize several objects
    baos = new ByteArrayOutputStream();
    jSONizeObjects(subscriptions, baos);
    bais = new ByteArrayInputStream(baos.toByteArray());
    desJSONizeAdvs(bais, subscriptions.length);

    //Size JSON with types
    String feature = "silbops-publisher";
    String type = "advertise";
    sizeJSONWithTypes(subscription, feature, type);
    sizeSeveralJSONWithTypes(subscriptions, feature, type);

    //Size JSON without types
    sizeJSONWithoutTypes(subscription);
    sizeSeveralJSONWithoutTypes(subscriptions);
}

From source file:com.mapr.synth.drive.Car.java

public double simulate(double t, GeoPoint currentPosition, Random rand, Segment segment, Callback progress) {
    double targetSpeed = segment.travelSpeed();
    double currentSpeed = 0;
    final double dt = 1;
    final double dv = 0.1 * Constants.G * dt;

    Vector3D start = currentPosition.as3D();
    double distanceToGo = currentPosition.distance(segment.end);
    engine.setDistance(0);/*from   www  .jav  a 2 s  .co  m*/
    Vector3D travelDirection = segment.end.as3D().subtract(currentPosition.as3D()).normalize();
    double previousDistance = distanceToGo;
    while (distanceToGo <= previousDistance) {
        if (rand.nextDouble() < 0.05) {
            targetSpeed = Math.max(20 * Constants.MPH, targetSpeed + (rand.nextInt(5) - 2) * 5 * Constants.MPH);
        }
        targetSpeed = Math.min(segment.maxSpeed(), targetSpeed);

        if (currentSpeed < targetSpeed) {
            currentSpeed += dv;
        } else {
            currentSpeed -= dv;
        }
        currentSpeed = Math.min(currentSpeed, maxSpeed(distanceToGo * 1000, segment.exitSpeed()));
        engine.stepToTime(t, currentSpeed, BRAKING_ACCELERATION);
        t += dt;
        currentPosition.setPosition(start
                .add(travelDirection.scalarMultiply(engine.getDistance() / 1000 / Constants.EARTH_RADIUS_KM)));
        progress.call(t, engine, currentPosition);
        previousDistance = distanceToGo;
        distanceToGo = currentPosition.distance(segment.end);
    }
    return t;
}

From source file:com.conwet.silbops.model.JSONvsRMIPerfT.java

@Test
public void testSubscription() {

    Subscription subscription = new Subscription().constrain("Test1", Type.DOUBLE).ge(50.0D)
            .constrain("Test2", Type.STRING).startsWith("TEST").subscription();

    Random random = new Random();
    Subscription[] subscriptions = new Subscription[1000 * 10];

    for (int i = 0; i < subscriptions.length; i++) {

        subscriptions[i] = new Subscription();
        subscriptions[i].constrain(toAttr(random.nextDouble())).ge(random.nextDouble());
        subscriptions[i].constrain(toAttr(random.nextDouble()))
                .startsWith(toAttr(random.nextDouble()).getName());
    }/* w w  w  .  j a v  a2 s.c om*/

    System.out.println("*****************TESTING FILTERS*****************");

    //Externalize and desexternalize one
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    externalizeObject(subscription, baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    desexternalizeObjects(bais, 1);

    //Externalize and desexternalize several
    baos = new ByteArrayOutputStream();
    externalizeSeveralObjects(subscriptions, baos);
    bais = new ByteArrayInputStream(baos.toByteArray());
    desexternalizeObjects(bais, subscriptions.length);

    //Size Externalize with types
    sizeExternalizeWithTypes(MessageType.SUBSCRIBE.name(), subscription);
    sizeExternalizeSeveralWithType(MessageType.SUBSCRIBE.name(), subscriptions);

    //Size Externalize without types
    sizeExternalizeWithoutTypes(subscription);
    sizeExternalizeSeveralWithoutTypes(subscriptions);

    //JSONize and desJSONize one object
    baos = new ByteArrayOutputStream();
    jSONizeObject(subscription, baos);
    bais = new ByteArrayInputStream(baos.toByteArray());
    desJSONizeSubscriptions(bais, 1);

    //JSONize and desJSONize several objects
    baos = new ByteArrayOutputStream();
    jSONizeObjects(subscriptions, baos);
    bais = new ByteArrayInputStream(baos.toByteArray());
    desJSONizeSubscriptions(bais, subscriptions.length);

    //Size JSON with types
    String feature = "silbops-subscriber";
    String type = "subscribe";
    sizeJSONWithTypes(subscription, feature, type);
    sizeSeveralJSONWithTypes(subscriptions, feature, type);

    //Size JSON without types
    sizeJSONWithoutTypes(subscription);
    sizeSeveralJSONWithoutTypes(subscriptions);
}

From source file:com.lfv.lanzius.application.AutoTester.java

public void run() {
    Random rand = new Random();

    try {//from ww w.  jav a2s .  c  om
        Thread.sleep(3000);

        startTime = System.currentTimeMillis();

        log.info(time() + " Starting auto tester");

        while (running) {
            List channelList = doc.getRootElement().getChild("ChannelSetup").getChildren();

            Element ec = (Element) channelList.get(rand.nextInt(channelList.size()));

            int channelId = DomTools.getAttributeInt(ec, "id", 0, false);

            if (DomTools.getAttributeBoolean(ec, "hidden", false, false))
                continue;

            double x = rand.nextDouble();

            // Change state
            if (x > 0.8) {
                if (DomTools.getAttributeBoolean(ec, "locked", false, false))
                    continue;

                boolean rx = rand.nextDouble() > 0.5;
                boolean tx = rand.nextDouble() > 0.5;

                log.info(time() + " rxtxStateUpdated(channelId=" + channelId + ", rx=" + rx + ", tx=" + tx
                        + ")");
                handler.rxtxStateUpdated(channelId, rx, tx);
            }

            // Push the channel
            else if (x > 0.6) {
                if (DomTools.getAttributeString(ec, "state", "off", false).equals("rxtx")) {
                    log.info(time() + " channelButtonPressed(channelId=" + channelId + ")");
                    handler.channelButtonPressed(channelId);
                    Thread.sleep((int) (rand.nextDouble() * 1500 + 500));
                    if (running) {
                        log.info(time() + " channelButtonReleased(channelId=" + channelId + ")");
                        handler.channelButtonReleased(channelId);
                    }
                }
            }

            // Push talk
            else if (x > 0.4) {
                log.info(time() + " talkButtonPressed(DEVICE_MOUSE)");
                handler.talkButtonPressed(Constants.DEVICE_MOUSE);
                Thread.sleep((int) (rand.nextDouble() * 1000 + 300));

                if (rand.nextDouble() < 0.3) {
                    log.info(time() + " talkButtonPressed(DEVICE_FTSW)");
                    handler.talkButtonPressed(Constants.DEVICE_FTSW);
                    Thread.sleep((int) (rand.nextDouble() * 1000 + 500));
                    if (running) {
                        log.info(time() + " talkButtonReleased(DEVICE_FTSW)");
                        handler.talkButtonReleased(Constants.DEVICE_FTSW);
                    }
                }

                if (running) {
                    Thread.sleep((int) (rand.nextDouble() * 1000 + 200));
                    log.info(time() + " talkButtonReleased(DEVICE_MOUSE)");
                    handler.talkButtonReleased(Constants.DEVICE_MOUSE);
                }
            }

            // Call phone
            else if (x > 0.2) {
                List roleList = doc.getRootElement().getChild("RoleSetup").getChildren();
                if (roleList.size() > 0) {
                    Element er = (Element) roleList.get(rand.nextInt(roleList.size()));

                    List peerList = er.getChild("PhonePeers").getChildren();
                    if (peerList != null) {
                        Element erp = (Element) peerList.get(rand.nextInt(peerList.size()));

                        int role = DomTools.getAttributeInt(er, "id", 0, false);
                        int peer = DomTools.getAttributeInt(erp, "id", 0, false);

                        log.info(time() + " dialButtonClicked(role=" + role + ", peer=" + peer + ")");
                        handler.dialButtonClicked(role, peer);
                    }
                }
            }

            // Pick up / Hang up phone
            else {
                log.info(time() + " hookButtonClicked()");
                handler.hookButtonClicked();
            }

            if (x > 0.8) {
                handler.isaValueChosen(rand.nextInt(10));
            }

            Thread.sleep((int) (rand.nextDouble() * 1000 + 100));
        }

        log.info(time() + " Stopping auto tester");

    } catch (Exception ex) {
        log.error("An unknown error occured", ex);
    }
}

From source file:UserInterface.QuickAssist.SeePatientDetailsJPanel.java

public void getLocation(double x0, double y0, int radius) {
    Random random = new Random();

    // Convert radius from meters to degrees
    double radiusInDegrees = radius / 111000f;

    double u = random.nextDouble();
    double v = random.nextDouble();
    double w = radiusInDegrees * Math.sqrt(u);
    double t = 2 * Math.PI * v;
    double x = w * Math.cos(t);
    double y = w * Math.sin(t);

    // Adjust the x-coordinate for the shrinking of the east-west distances
    double new_x = x / Math.cos(y0);

    patLong = new_x + x0;
    patLat = y + y0;/* w ww . j a  va  2s  . c  o m*/
}