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.jtransforms.utils.IOUtils.java

/**
 * Fills 3D matrix with random numbers.//from w w  w.j a v a2 s.c o  m
* @param n1  slices
* @param n2  rows
* @param n3  columns
* @param m   3D matrix
*/
public static void fillMatrix_3D(long n1, long n2, long n3, float[][][] m) {
    Random r = new Random(2);
    for (int i = 0; i < n1; i++) {
        for (int j = 0; j < n2; j++) {
            for (int k = 0; k < n3; k++) {
                m[i][j][k] = r.nextFloat();
            }
        }
    }
}

From source file:com.linkedin.pinot.core.data.readers.BackfillDateTimeRecordReaderTest.java

private List<GenericRow> createTestDataWithTimespec(TimeFieldSpec timeFieldSpec) {
    List<GenericRow> rows = new ArrayList<>();
    Random random = new Random();

    Map<String, Object> fields;
    for (int i = 0; i < NUM_ROWS; i++) {
        fields = new HashMap<>();
        fields.put(D1, RandomStringUtils.randomAlphabetic(2));
        fields.put(D2, RandomStringUtils.randomAlphabetic(5));
        fields.put(M1, Math.abs(random.nextInt()));
        fields.put(M2, Math.abs(random.nextFloat()));

        long timestamp = System.currentTimeMillis();
        Object timeColumnValue = timeFieldSpec.getIncomingGranularitySpec().fromMillis(timestamp);
        fields.put(timeFieldSpec.getName(), timeColumnValue);

        GenericRow row = new GenericRow();
        row.init(fields);//from   w  ww  .ja v  a2s  .  c o m
        rows.add(row);
    }
    return rows;
}

From source file:com.linkedin.pinot.core.data.readers.BackfillDateTimeRecordReaderTest.java

private List<GenericRow> createTestDataWithTimespec(TimeFieldSpec timeFieldSpec,
        DateTimeFieldSpec dateTimeFieldSpec) {
    List<GenericRow> rows = new ArrayList<>();
    Random random = new Random();

    Map<String, Object> fields;
    for (int i = 0; i < NUM_ROWS; i++) {
        fields = new HashMap<>();
        fields.put(D1, RandomStringUtils.randomAlphabetic(2));
        fields.put(D2, RandomStringUtils.randomAlphabetic(5));
        fields.put(M1, Math.abs(random.nextInt()));
        fields.put(M2, Math.abs(random.nextFloat()));

        long timestamp = System.currentTimeMillis();
        Object timeColumnValue = timeFieldSpec.getIncomingGranularitySpec().fromMillis(timestamp);
        fields.put(timeFieldSpec.getName(), timeColumnValue);

        DateTimeFormatSpec toFormat = new DateTimeFormatSpec(dateTimeFieldSpec.getFormat());
        Object dateTimeColumnValue = toFormat.fromMillisToFormat(timestamp, Object.class);
        fields.put(dateTimeFieldSpec.getName(), dateTimeColumnValue);

        GenericRow row = new GenericRow();
        row.init(fields);//from   w w  w .ja  va  2s. c  o m
        rows.add(row);
    }
    return rows;
}

From source file:com.abhinavjhanwar.android.egg.neko.Cat.java

public Cat(Context context, long seed, List<Cat> mCats) {
    D = new CatParts(context);
    mSeed = seed;/*ww  w  . ja v a2s  .  c o  m*/
    long check = seed;
    for (int i = 0; i < mCats.size(); i++) {
        while (context.getString(R.string.default_cat_name, String.valueOf(check).substring(0, 3))
                .equals(mCats.get(i).getName())) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                check = Math.abs(ThreadLocalRandom.current().nextInt());
            } else {
                check = Math.abs(new Random().nextInt());
            }
        }
    }

    setName(context.getString(R.string.default_cat_name, String.valueOf(check).substring(0, 3)));

    final Random nsr = notSoRandom(seed);

    // body color
    mBodyColor = chooseP(nsr, P_BODY_COLORS);
    if (mBodyColor == 0)
        mBodyColor = Color.HSVToColor(new float[] { nsr.nextFloat() * 360f, frandrange(nsr), frandrange(nsr) });

    tint(mBodyColor, D.body, D.head, D.leg1, D.leg2, D.leg3, D.leg4, D.tail, D.leftEar, D.rightEar, D.foot1,
            D.foot2, D.foot3, D.foot4, D.tailCap);
    tint(0x20000000, D.leg2Shadow, D.tailShadow);
    if (isDark(mBodyColor)) {
        tint(0xFFFFFFFF, D.leftEye, D.rightEye, D.mouth, D.nose);
    }
    tint(isDark(mBodyColor) ? 0xFFEF9A9A : 0x20D50000, D.leftEarInside, D.rightEarInside);

    tint(chooseP(nsr, P_BELLY_COLORS), D.belly);
    tint(chooseP(nsr, P_BELLY_COLORS), D.back);
    final int faceColor = chooseP(nsr, P_BELLY_COLORS);
    tint(faceColor, D.faceSpot);
    if (!isDark(faceColor)) {
        tint(0xFF000000, D.mouth, D.nose);
    }

    if (nsr.nextFloat() < 0.25f) {
        tint(0xFFFFFFFF, D.foot1, D.foot2, D.foot3, D.foot4);
    } else {
        if (nsr.nextFloat() < 0.25f) {
            tint(0xFFFFFFFF, D.foot1, D.foot2);
        } else if (nsr.nextFloat() < 0.25f) {
            tint(0xFFFFFFFF, D.foot3, D.foot4);
        } else if (nsr.nextFloat() < 0.1f) {
            tint(0xFFFFFFFF, (Drawable) choose(nsr, D.foot1, D.foot2, D.foot3, D.foot4));
        }
    }

    tint(nsr.nextFloat() < 0.333f ? 0xFFFFFFFF : mBodyColor, D.tailCap);

    final int capColor = chooseP(nsr, isDark(mBodyColor) ? P_LIGHT_SPOT_COLORS : P_DARK_SPOT_COLORS);
    tint(capColor, D.cap);
    //tint(chooseP(nsr, isDark(bodyColor) ? P_LIGHT_SPOT_COLORS : P_DARK_SPOT_COLORS), D.nose);

    final int collarColor = chooseP(nsr, P_COLLAR_COLORS);
    tint(collarColor, D.collar);
    tint((nsr.nextFloat() < 0.1f) ? collarColor : 0, D.bowtie);
}

From source file:io.galeb.router.tests.hostselectors.GuavaConsistentHashTest.java

@Test
public void checkUniformDistribution() {
    final long samples = 100000L;
    final int rounds = 5;
    final double percentMarginOfError = 0.5;
    final int numKeys = 100;
    final Random random = new Random();

    for (int round = 0; round < rounds; round++) {
        logger.info(String.format("checkUniformDistribution - round %s: %d samples", round + 1, samples));

        for (final HashFunction hash : new HashFunction[] { md5(), murmur3_128(), sipHash24(), sha256() }) {
            long sum = 0L;
            final long initialTime = System.currentTimeMillis();
            for (Integer counter = 0; counter < samples; counter++) {
                final int chosen = (int) (random.nextFloat() * (numKeys - Float.MIN_VALUE));
                sum += Hashing.consistentHash(hash.hashInt(chosen), (int) numBackends);
            }/*w  ww. j a va  2 s.c o m*/

            final long finishTime = System.currentTimeMillis();

            final double result = (numBackends * (numBackends - 1) / 2.0) * (samples / numBackends);

            logger.info(String.format(
                    "-> checkUniformDistribution (%s): Time spent (ms): %d. NonUniformDistRatio (smaller is better): %.4f%%",
                    hash, finishTime - initialTime, Math.abs(100.0 * (result - sum) / result)));

            final double topLimit = sum * (1.0 + percentMarginOfError);
            final double bottomLimit = sum * (1.0 - percentMarginOfError);

            try {
                assertThat(result).isGreaterThanOrEqualTo(bottomLimit).isLessThanOrEqualTo(topLimit);
            } catch (AssertionError e) {
                logger.error("Error when testing " + hash);
                throw e;
            }
        }
    }
}

From source file:org.apache.hadoop.hbase.procedure2.store.wal.ProcedureWALLoaderPerformanceEvaluation.java

/**
 * @return a list of shuffled integers which represent state of proc id. First occurrence of a
 * number denotes insert state, consecutive occurrences denote update states, and -ve value
 * denotes delete state.//from   ww w .j  a va2  s. c o  m
 */
private List<Integer> shuffleProcWriteSequence() {
    Random rand = new Random();
    List<Integer> procStatesSequence = new ArrayList<>();
    Set<Integer> toBeDeletedProcs = new HashSet<>();
    // Add n + 1 entries of the proc id for insert + updates. If proc is chosen for delete, add
    // extra entry which is marked -ve in the loop after shuffle.
    for (int procId = 1; procId <= numProcs; ++procId) {
        procStatesSequence.addAll(Collections.nCopies(updatesPerProc + 1, procId));
        if (rand.nextFloat() < deleteProcsFraction) {
            procStatesSequence.add(procId);
            toBeDeletedProcs.add(procId);
        }
    }
    Collections.shuffle(procStatesSequence);
    // Mark last occurrences of proc ids in toBeDeletedProcs with -ve to denote it's a delete state.
    for (int i = procStatesSequence.size() - 1; i >= 0; --i) {
        int procId = procStatesSequence.get(i);
        if (toBeDeletedProcs.contains(procId)) {
            procStatesSequence.set(i, -1 * procId);
            toBeDeletedProcs.remove(procId);
        }
    }
    return procStatesSequence;
}

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

/**
 * Fills 3D matrix with random numbers./*from  ww  w .j a va  2  s .co  m*/
* @param n1  slices
* @param n2  rows
* @param n3  columns
* @param m   3D matrix
*/
public static void fillMatrix_3D(long n1, long n2, long n3, float[] m) {
    Random r = new Random(2);
    long sliceStride = n2 * n3;
    long rowStride = n3;
    for (int i = 0; i < n1; i++) {
        for (int j = 0; j < n2; j++) {
            for (int k = 0; k < n3; k++) {
                m[(int) (i * sliceStride + j * rowStride + k)] = r.nextFloat();
            }
        }
    }
}

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

/**
 * Fills 3D matrix with random numbers.//from  w w w.  j  a va  2 s . c  o m
* @param n1  slices
* @param n2  rows
* @param n3  columns
* @param m   3D matrix
*/
public static void fillMatrix_3D(long n1, long n2, long n3, FloatLargeArray m) {
    Random r = new Random(2);
    long sliceStride = n2 * n3;
    long rowStride = n3;
    for (long i = 0; i < n1; i++) {
        for (long j = 0; j < n2; j++) {
            for (long k = 0; k < n3; k++) {
                m.setDouble(i * sliceStride + j * rowStride + k, r.nextFloat());
            }
        }
    }
}

From source file:com.linkedin.pinot.core.data.readers.PinotSegmentRecordReaderTest.java

private List<GenericRow> createTestData() {
    List<GenericRow> rows = new ArrayList<>();
    Random random = new Random();

    Map<String, Object> fields;
    for (int i = 0; i < 10000; i++) {
        fields = new HashMap<>();
        fields.put(D_SV_1, D_SV_1 + "_" + RandomStringUtils.randomAlphabetic(2));
        Object[] d2Array = new Object[5];
        for (int j = 0; j < 5; j++) {
            d2Array[j] = D_MV_1 + "_" + j + "_" + RandomStringUtils.randomAlphabetic(2);
        }/*from   ww  w.  ja  va  2  s  .c  o m*/
        fields.put(D_MV_1, d2Array);
        fields.put(M1, Math.abs(random.nextInt()));
        fields.put(M2, Math.abs(random.nextFloat()));
        fields.put(TIME, Math.abs(random.nextLong()));

        GenericRow row = new GenericRow();
        row.init(fields);
        rows.add(row);
    }
    return rows;
}

From source file:co.cask.hydrator.plugin.batch.aggreagtor.aggregator.Sampling.java

@Override
public void aggregate(String groupKey, Iterator<StructuredRecord> iterator, Emitter<StructuredRecord> emitter)
        throws Exception {
    int finalSampleSize = 0;
    if (config.sampleSize != null) {
        finalSampleSize = config.sampleSize;
    }/*  w w w  .  ja v a 2  s . c o  m*/
    if (config.samplePercentage != null) {
        finalSampleSize = Math.round((config.samplePercentage / 100) * config.totalRecords);
    }

    switch (TYPE.valueOf(config.samplingType.toUpperCase())) {
    case SYSTEMATIC:
        if (config.overSamplingPercentage != null) {
            finalSampleSize = Math
                    .round(finalSampleSize + (finalSampleSize * (config.overSamplingPercentage / 100)));
        }

        int sampleIndex = Math.round(config.totalRecords / finalSampleSize);
        Float random = new Float(0);
        if (config.random != null) {
            random = config.random;
        } else {
            random = new Random().nextFloat();
        }
        int firstSampleIndex = Math.round(sampleIndex * random);
        List<StructuredRecord> records = IteratorUtils.toList(iterator);
        int counter = 0;
        emitter.emit(records.get(firstSampleIndex));
        counter++;

        while (counter < finalSampleSize) {
            int index = firstSampleIndex + (counter * sampleIndex);
            emitter.emit(records.get(index - 1));
            counter++;
        }
        break;

    case RESERVOIR:
        PriorityBuffer sampleData = new PriorityBuffer(true, new Comparator<StructuredRecord>() {
            @Override
            public int compare(StructuredRecord o1, StructuredRecord o2) {
                if ((float) o1.get("random") < (float) o2.get("random")) {
                    return 1;
                } else if ((float) o1.get("random") > (float) o2.get("random")) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });

        int count = 0;
        Random randomValue = new Random();
        List<StructuredRecord> recordArray = IteratorUtils.toList(iterator);
        Schema inputSchema = recordArray.get(0).getSchema();
        Schema schemaWithRandomField = createSchemaWithRandomField(inputSchema);
        while (count < finalSampleSize) {
            StructuredRecord record = recordArray.get(0);
            sampleData.add(getSampledRecord(record, randomValue.nextFloat(), schemaWithRandomField));
            count++;
        }

        while (count < recordArray.size()) {
            StructuredRecord structuredRecord = (StructuredRecord) sampleData.get();
            Float randomFloat = randomValue.nextFloat();
            if ((float) structuredRecord.get("random") < randomFloat) {
                sampleData.remove();
                StructuredRecord record = recordArray.get(count);
                sampleData.add(getSampledRecord(record, randomFloat, structuredRecord.getSchema()));
            }
            count++;
        }

        Iterator<StructuredRecord> sampleDataIterator = sampleData.iterator();
        while (sampleDataIterator.hasNext()) {
            StructuredRecord sampledRecord = sampleDataIterator.next();
            StructuredRecord.Builder builder = StructuredRecord.builder(inputSchema);
            for (Schema.Field field : sampledRecord.getSchema().getFields()) {
                if (!field.getName().equalsIgnoreCase("random")) {
                    builder.set(field.getName(), sampledRecord.get(field.getName()));
                }
            }
            emitter.emit(builder.build());
        }
        break;
    }
}