Example usage for java.util Random nextFloat

List of usage examples for java.util Random nextFloat

Introduction

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

Prototype

public float nextFloat() 

Source Link

Document

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

Usage

From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java

protected void noiseEffects(Graphics2D gfx, BufferedImage image) {
    // XOR circle
    int dx = randomInt(width, 2 * width);
    int dy = randomInt(width, 2 * height);
    int x = randomInt(0, width / 2);
    int y = randomInt(0, height / 2);

    gfx.setXORMode(Color.GRAY);/*from  ww w.j a v  a2  s. co m*/
    if (config.isFontSizeRandom())
        gfx.setStroke(new BasicStroke(randomInt(config.getFontSize() / 8, config.getFontSize() / 2)));
    else
        gfx.setStroke(new BasicStroke(config.getFontSize()));

    gfx.drawOval(x, y, dx, dy);

    WritableRaster rstr = image.getRaster();
    int[] vColor = new int[3];
    int[] oldColor = new int[3];
    Random vRandom = new Random(System.currentTimeMillis());
    // noise
    for (x = 0; x < width; x++) {
        for (y = 0; y < height; y++) {
            rstr.getPixel(x, y, oldColor);

            // hard noise
            vColor[0] = 0 + (int) (Math.floor(vRandom.nextFloat() * 1.03) * 255);
            // soft noise
            vColor[0] = vColor[0] ^ (170 + (int) (vRandom.nextFloat() * 80));
            // xor to image
            vColor[0] = vColor[0] ^ oldColor[0];
            vColor[1] = vColor[0];
            vColor[2] = vColor[0];

            rstr.setPixel(x, y, vColor);
        }
    }
}

From source file:org.apache.hadoop.mapreduce.TestMapCollection.java

@Test
public void testRandom() throws Exception {
    Configuration conf = new Configuration();
    conf.setInt(Job.COMPLETION_POLL_INTERVAL_KEY, 100);
    Job job = Job.getInstance(conf);/*w  ww .j a v  a  2 s  . c  om*/
    conf = job.getConfiguration();
    conf.setInt(MRJobConfig.IO_SORT_MB, 1);
    conf.setClass("test.mapcollection.class", RandomFactory.class, RecordFactory.class);
    final Random r = new Random();
    final long seed = r.nextLong();
    LOG.info("SEED: " + seed);
    r.setSeed(seed);
    conf.set(MRJobConfig.MAP_SORT_SPILL_PERCENT, Float.toString(Math.max(0.1f, r.nextFloat())));
    RandomFactory.setLengths(conf, r, 1 << 14);
    conf.setInt("test.spillmap.records", r.nextInt(500));
    conf.setLong("test.randomfactory.seed", r.nextLong());
    runTest("random", job);
}

From source file:org.apache.hadoop.mapreduce.TestMapCollection.java

@Test
public void testRandomCompress() throws Exception {
    Configuration conf = new Configuration();
    conf.setInt(Job.COMPLETION_POLL_INTERVAL_KEY, 100);
    Job job = Job.getInstance(conf);//from w  w  w .  j a v  a 2  s .c o m
    conf = job.getConfiguration();
    conf.setInt(MRJobConfig.IO_SORT_MB, 1);
    conf.setBoolean(MRJobConfig.MAP_OUTPUT_COMPRESS, true);
    conf.setClass("test.mapcollection.class", RandomFactory.class, RecordFactory.class);
    final Random r = new Random();
    final long seed = r.nextLong();
    LOG.info("SEED: " + seed);
    r.setSeed(seed);
    conf.set(MRJobConfig.MAP_SORT_SPILL_PERCENT, Float.toString(Math.max(0.1f, r.nextFloat())));
    RandomFactory.setLengths(conf, r, 1 << 14);
    conf.setInt("test.spillmap.records", r.nextInt(500));
    conf.setLong("test.randomfactory.seed", r.nextLong());
    runTest("randomCompress", job);
}

From source file:org.deeplearning4j.examples.multigpu.video.VideoGenerator.java

private static int[] generateVideo(String path, int nFrames, int width, int height, int numShapes, Random r,
        boolean backgroundNoise, int numDistractorsPerFrame) throws Exception {

    //First: decide where transitions between one shape and another are
    double[] rns = new double[numShapes];
    double sum = 0;
    for (int i = 0; i < numShapes; i++) {
        rns[i] = r.nextDouble();/*w  w w  .  j  a v  a2s .c om*/
        sum += rns[i];
    }
    for (int i = 0; i < numShapes; i++)
        rns[i] /= sum;

    int[] startFrames = new int[numShapes];
    startFrames[0] = 0;
    for (int i = 1; i < numShapes; i++) {
        startFrames[i] = (int) (startFrames[i - 1] + MIN_FRAMES + rns[i] * (nFrames - numShapes * MIN_FRAMES));
    }

    //Randomly generate shape positions, velocities, colors, and type
    int[] shapeTypes = new int[numShapes];
    int[] initialX = new int[numShapes];
    int[] initialY = new int[numShapes];
    double[] velocityX = new double[numShapes];
    double[] velocityY = new double[numShapes];
    Color[] color = new Color[numShapes];
    for (int i = 0; i < numShapes; i++) {
        shapeTypes[i] = r.nextInt(NUM_SHAPES);
        initialX[i] = SHAPE_MIN_DIST_FROM_EDGE + r.nextInt(width - SHAPE_SIZE - 2 * SHAPE_MIN_DIST_FROM_EDGE);
        initialY[i] = SHAPE_MIN_DIST_FROM_EDGE + r.nextInt(height - SHAPE_SIZE - 2 * SHAPE_MIN_DIST_FROM_EDGE);
        velocityX[i] = -1 + 2 * r.nextDouble();
        velocityY[i] = -1 + 2 * r.nextDouble();
        color[i] = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat());
    }

    //Generate a sequence of BufferedImages with the given shapes, and write them to the video
    SequenceEncoder enc = new SequenceEncoder(new File(path));
    int currShape = 0;
    int[] labels = new int[nFrames];
    for (int i = 0; i < nFrames; i++) {
        if (currShape < numShapes - 1 && i >= startFrames[currShape + 1])
            currShape++;

        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bi.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setBackground(Color.BLACK);

        if (backgroundNoise) {
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    bi.setRGB(x, y, new Color(r.nextFloat() * MAX_NOISE_VALUE, r.nextFloat() * MAX_NOISE_VALUE,
                            r.nextFloat() * MAX_NOISE_VALUE).getRGB());
                }
            }
        }

        g2d.setColor(color[currShape]);

        //Position of shape this frame
        int currX = (int) (initialX[currShape]
                + (i - startFrames[currShape]) * velocityX[currShape] * MAX_VELOCITY);
        int currY = (int) (initialY[currShape]
                + (i - startFrames[currShape]) * velocityY[currShape] * MAX_VELOCITY);

        //Render the shape
        switch (shapeTypes[currShape]) {
        case 0:
            //Circle
            g2d.fill(new Ellipse2D.Double(currX, currY, SHAPE_SIZE, SHAPE_SIZE));
            break;
        case 1:
            //Square
            g2d.fill(new Rectangle2D.Double(currX, currY, SHAPE_SIZE, SHAPE_SIZE));
            break;
        case 2:
            //Arc
            g2d.fill(new Arc2D.Double(currX, currY, SHAPE_SIZE, SHAPE_SIZE, 315, 225, Arc2D.PIE));
            break;
        case 3:
            //Line
            g2d.setStroke(lineStroke);
            g2d.draw(new Line2D.Double(currX, currY, currX + SHAPE_SIZE, currY + SHAPE_SIZE));
            break;
        default:
            throw new RuntimeException();
        }

        //Add some distractor shapes, which are present for one frame only
        for (int j = 0; j < numDistractorsPerFrame; j++) {
            int distractorShapeIdx = r.nextInt(NUM_SHAPES);

            int distractorX = DISTRACTOR_MIN_DIST_FROM_EDGE + r.nextInt(width - SHAPE_SIZE);
            int distractorY = DISTRACTOR_MIN_DIST_FROM_EDGE + r.nextInt(height - SHAPE_SIZE);

            g2d.setColor(new Color(r.nextFloat(), r.nextFloat(), r.nextFloat()));

            switch (distractorShapeIdx) {
            case 0:
                g2d.fill(new Ellipse2D.Double(distractorX, distractorY, SHAPE_SIZE, SHAPE_SIZE));
                break;
            case 1:
                g2d.fill(new Rectangle2D.Double(distractorX, distractorY, SHAPE_SIZE, SHAPE_SIZE));
                break;
            case 2:
                g2d.fill(new Arc2D.Double(distractorX, distractorY, SHAPE_SIZE, SHAPE_SIZE, 315, 225,
                        Arc2D.PIE));
                break;
            case 3:
                g2d.setStroke(lineStroke);
                g2d.draw(new Line2D.Double(distractorX, distractorY, distractorX + SHAPE_SIZE,
                        distractorY + SHAPE_SIZE));
                break;
            default:
                throw new RuntimeException();
            }
        }

        enc.encodeImage(bi);
        g2d.dispose();
        labels[i] = shapeTypes[currShape];
    }
    enc.finish(); //write .mp4

    return labels;
}

From source file:org.apache.hadoop.hive.serde2.binarysortable.MyTestClass.java

public int randomFill(Random r, ExtraTypeInfo extraTypeInfo) {
    int randField = r.nextInt(MyTestClass.fieldCount);
    int field = 0;

    myBool = (randField == field++) ? null : (r.nextInt(1) == 1);
    myByte = (randField == field++) ? null : Byte.valueOf((byte) r.nextInt());
    myShort = (randField == field++) ? null : Short.valueOf((short) r.nextInt());
    myInt = (randField == field++) ? null : Integer.valueOf(r.nextInt());
    myLong = (randField == field++) ? null : Long.valueOf(r.nextLong());
    myFloat = (randField == field++) ? null : Float.valueOf(r.nextFloat() * 10 - 5);
    myDouble = (randField == field++) ? null : Double.valueOf(r.nextDouble() * 10 - 5);
    myString = (randField == field++) ? null : MyTestPrimitiveClass.getRandString(r);
    myHiveChar = (randField == field++) ? null : MyTestPrimitiveClass.getRandHiveChar(r, extraTypeInfo);
    myHiveVarchar = (randField == field++) ? null : MyTestPrimitiveClass.getRandHiveVarchar(r, extraTypeInfo);
    myBinary = MyTestPrimitiveClass.getRandBinary(r, r.nextInt(1000));
    myDecimal = (randField == field++) ? null : MyTestPrimitiveClass.getRandHiveDecimal(r, extraTypeInfo);
    myDate = (randField == field++) ? null : MyTestPrimitiveClass.getRandDate(r);
    myTimestamp = (randField == field++) ? null : RandomTypeUtil.getRandTimestamp(r);
    myIntervalYearMonth = (randField == field++) ? null : MyTestPrimitiveClass.getRandIntervalYearMonth(r);
    myIntervalDayTime = (randField == field++) ? null : MyTestPrimitiveClass.getRandIntervalDayTime(r);

    myStruct = (randField == field++) ? null : new MyTestInnerStruct(r.nextInt(5) - 2, r.nextInt(5) - 2);
    myList = (randField == field++) ? null : getRandIntegerArray(r);
    return field;
}

From source file:org.apache.hadoop.hbase.master.TestRegionPlacement.java

/**
 * Used to test the correctness of this class.
 *///from w w  w  . ja  v  a2s . c  o m
@Test
public void testRandomizedMatrix() {
    int rows = 100;
    int cols = 100;
    float[][] matrix = new float[rows][cols];
    Random random = new Random();
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = random.nextFloat();
        }
    }

    // Test that inverting a transformed matrix gives the original matrix.
    RegionPlacementMaintainer.RandomizedMatrix rm = new RegionPlacementMaintainer.RandomizedMatrix(rows, cols);
    float[][] transformed = rm.transform(matrix);
    float[][] invertedTransformed = rm.invert(transformed);
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (matrix[i][j] != invertedTransformed[i][j]) {
                throw new RuntimeException();
            }
        }
    }

    // Test that the indices on a transformed matrix can be inverted to give
    // the same values on the original matrix.
    int[] transformedIndices = new int[rows];
    for (int i = 0; i < rows; i++) {
        transformedIndices[i] = random.nextInt(cols);
    }
    int[] invertedTransformedIndices = rm.invertIndices(transformedIndices);
    float[] transformedValues = new float[rows];
    float[] invertedTransformedValues = new float[rows];
    for (int i = 0; i < rows; i++) {
        transformedValues[i] = transformed[i][transformedIndices[i]];
        invertedTransformedValues[i] = matrix[i][invertedTransformedIndices[i]];
    }
    Arrays.sort(transformedValues);
    Arrays.sort(invertedTransformedValues);
    if (!Arrays.equals(transformedValues, invertedTransformedValues)) {
        throw new RuntimeException();
    }
}

From source file:dremel.common.AvroTest.java

@SuppressWarnings(value = "unchecked")
private static Object generateRandomDataRecursive(Schema schema, Random random, int size) {
    switch (schema.getType()) {
    case RECORD:// w w w.ja  v a2s  .  co  m
        GenericRecord record = new GenericData.Record(schema);
        boolean isFieldsEmpty = true;
        for (Schema.Field field : schema.getFields()) {
            Object o = generateRandomDataRecursive(field.schema(), random, size);
            if (o != null) {
                record.put(field.name(), o);
                isFieldsEmpty = isFieldsEmpty && o instanceof GenericArray
                        && ((GenericArray<Object>) o).size() == 0;
            }
        }
        return isFieldsEmpty ? null : record;
    case ARRAY:
        int length = size + (random.nextInt(10));
        GenericArray<Object> array = new GenericData.Array<Object>(length <= 0 ? 0 : length, schema);
        Object o;
        for (int i = 0; i < length; i++) {
            o = generateRandomDataRecursive(schema.getElementType(), random, size > 0 ? size - 1 : 0);
            if (o != null)
                array.add(o);
        }
        return array;
    case STRING:
        return generateRandomUtf8(random, 40);
    case INT:
        return random.nextInt();
    case LONG:
        return random.nextLong();
    case FLOAT:
        return random.nextFloat();
    case DOUBLE:
        return random.nextDouble();
    case BOOLEAN:
        return random.nextBoolean();
    default:
        throw new RuntimeException("Unknown type: " + schema);
    }
}

From source file:com.pivotal.gemfire.tools.pulse.testbed.PropMockDataUpdater.java

private void refresh(Member m) {
    if (LOGGER.infoEnabled()) {
        LOGGER.info(resourceBundle.getString("LOG_MSG_REFRESHING_MEMBER_DATA") + " : " + m.getName());
    }// ww  w  . j  a  va2  s  . c  om

    Random r = new Random(System.currentTimeMillis());

    m.setUptime(System.currentTimeMillis());
    m.setQueueBacklog("" + Math.abs(r.nextInt(500)));
    m.setCurrentHeapSize(Math.abs(r.nextInt(Math.abs((int) m.getMaxHeapSize()))));
    m.setTotalDiskUsage(Math.abs(r.nextInt(100)));

    Float cpuUsage = r.nextFloat() * 100;
    m.getCpuUsageSamples().add(cpuUsage);
    m.setCpuUsage(cpuUsage);

    m.getHeapUsageSamples().add(m.getCurrentHeapSize());
    m.setLoadAverage((double) Math.abs(r.nextInt(100)));
    m.setNumThreads(Math.abs(r.nextInt(100)));
    m.setGarbageCollectionCount((long) Math.abs(r.nextInt(100)));
    m.getGarbageCollectionSamples().add(m.getGarbageCollectionCount());

    m.setTotalFileDescriptorOpen((long) Math.abs(r.nextInt(100)));

    m.setThroughputWrites(Math.abs(r.nextInt(10)));
    m.getThroughputWritesTrend().add(m.getThroughputWrites());

    m.setGetsRate(Math.abs(r.nextInt(5000)));
    m.getGetsPerSecond().add(m.getGetsRate());

    m.setPutsRate(Math.abs(r.nextInt(5000)));
    m.getPutsPerSecond().add(m.getPutsRate());

    Alert[] alerts = cluster.getAlertsList();
    List<Alert> alertsList = new ArrayList<Alert>(Arrays.asList(alerts));

    if (r.nextBoolean()) {
        // Generate alerts
        if (r.nextBoolean()) {
            if (r.nextInt(10) > 5) {
                alertsList.add(createAlert(Alert.SEVERE, m.getName(), alertsList.size()));
                if (alertsList.size() > ALERTS_MAX_SIZE) {
                    alertsList.remove(0);
                }
            }
        }

        if (r.nextBoolean()) {
            if (r.nextInt(10) > 5) {
                alertsList.add(createAlert(Alert.ERROR, m.getName(), alertsList.size()));
                if (alertsList.size() > ALERTS_MAX_SIZE) {
                    alertsList.remove(0);
                }
            }
        }

        if (r.nextBoolean()) {
            if (r.nextInt(10) > 5) {
                alertsList.add(createAlert(Alert.WARNING, m.getName(), alertsList.size()));
                if (alertsList.size() > ALERTS_MAX_SIZE) {
                    alertsList.remove(0);
                }
            }
        }
    }
}

From source file:com.galactogolf.specificobjectmodel.GalactoGolfWorld.java

@Override
public void LoadLevel(LevelDefinition level) throws LevelLoadingException {
    _renderablesLoaded = false;/*from   ww  w  . j  ava 2  s  . com*/
    _runningPhysics = false;
    _previousPowerLineSet = false;
    super.LoadLevel(level);

    _probePowerLine = new LineElement();

    this._player = new GalactoGolfPlayerEntity(this);
    ((GalactoGolfPlayerEntity) this._player).getVelocity().x = 0.0f;
    ((GalactoGolfPlayerEntity) this._player).getVelocity().y = 0.1f;
    this._player.getPosition().x = 600.0f;
    this._player.getPosition().y = 350.0f;

    _gravityWells = new ArrayList<NonPlayerEntity>();
    LevelDefinitionWorldConverter.LoadLevelDefinitionIntoWorld(level, this);

    // generate star field
    Random rnd = new Random();
    _stars = new ArrayList<StarSprite>();
    for (int i = 0; i < 200; i++) {
        StarSprite star;
        if (i % 2 == 0) {
            star = new StarSprite();
        } else {
            star = new StarSprite2();

        }
        star.setPosition(new Vector2D(rnd.nextFloat() * 2000 - 1000, rnd.nextFloat() * 2000 - 1000));
        _stars.add(star);
    }

    _hazeSprite = new HazeSprite();

    _score = 0;
    _bonus = 0;
    _powerArrow = new ArrowSprite();
    _powerArrow.getPosition().x = this.GetPlayer().getPosition().x;
    _powerArrow.getPosition().y = this.GetPlayer().getPosition().y;

    if (level.getDescription() != null && level.getDescription().length() > 0) {
        _parentActivity.ShowMessagePopup(level.getName(), level.getDescription());
    }
}

From source file:forge.ai.ComputerUtil.java

public static boolean preventRunAwayActivations(final SpellAbility sa) {
    int activations = sa.getRestrictions().getNumberTurnActivations();

    if (sa.isTemporary()) {
        final Random r = MyRandom.getRandom();
        return r.nextFloat() >= .95; // Abilities created by static abilities have no memory
    }//  w w  w.  j av  a 2 s.c o m

    if (activations < 10) { //10 activations per turn should still be acceptable
        return false;
    }

    final Random r = MyRandom.getRandom();
    return r.nextFloat() >= Math.pow(.95, activations);
}