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.asakusafw.runtime.stage.input.DefaultSplitCombiner.java

private static void mutate(Environment env, Gene gene) {
    Random random = env.random;
    int[] schema = gene.schema;
    double mutations = env.mutations;
    for (int i = 0; i < schema.length; i++) {
        if (random.nextDouble() < mutations) {
            schema[i] = random.nextInt(env.slots.length);
        }//from w w  w  .  ja  v a  2  s. c om
    }
}

From source file:main.Driver.java

/**
 * Given a primary queue, a reference leadsheet for chords, and a corpus of queue files, construct the result leadsheet from a series of randomly weighted interpolations of the primary queue towards the set of selected queues.
 * @param autoencoder/*from w w w  . jav a2s . c  o  m*/
 * @param autoencoderConnectomePath
 * @param primaryQueuePath
 * @param queueFolder
 * @param outputFilePath
 * @param chordSequence
 * @param numReferenceQueues
 * @param numCombinations
 * @param interpolationMagnitude 
 */
public static void frankensteinTest(ProductCompressingAutoencoder autoencoder, String autoencoderConnectomePath,
        String primaryQueuePath, File queueFolder, String outputFilePath, LeadsheetDataSequence chordSequence,
        int numReferenceQueues, int numCombinations, double interpolationMagnitude) {
    LogTimer.startLog("Loading queues");

    if (queueFolder.isDirectory()) {
        File[] queueFiles = queueFolder.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.contains(".q");
            }
        });

        List<File> fileList = new ArrayList<>();
        for (File file : queueFiles) {
            fileList.add(file);
        }
        Collections.shuffle(fileList);
        int numSelectedFiles = (numReferenceQueues > queueFiles.length) ? queueFiles.length
                : numReferenceQueues;

        for (int i = 0; i < queueFiles.length - numSelectedFiles; i++) {
            fileList.remove(fileList.size() - 1);
        }
        List<FragmentedNeuralQueue> queuePopulation = new ArrayList<>(fileList.size());
        String songTitle = "A mix of ";
        for (File file : fileList) {
            FragmentedNeuralQueue newQueue = new FragmentedNeuralQueue();
            newQueue.initFromFile(file.getPath());
            queuePopulation.add(newQueue);
            songTitle += file.getName().replaceAll(".q", "") + ", ";
        }
        LogTimer.endLog();

        LeadsheetDataSequence outputSequence = chordSequence.copy();
        LeadsheetDataSequence additionalOutput = chordSequence.copy();
        for (int i = 1; i < numCombinations; i++) {
            outputSequence.concat(additionalOutput.copy());
        }
        LeadsheetDataSequence decoderInputSequence = outputSequence.copy();

        FragmentedNeuralQueue primaryQueue = new FragmentedNeuralQueue();
        primaryQueue.initFromFile(primaryQueuePath);

        for (int i = 0; i < numCombinations; i++) {

            LogTimer.startLog("Performing queue interpolation...");
            AVector combinationStrengths = Vector.createLength(queuePopulation.size());
            Random vectorRand = new Random(i);
            for (int j = 0; j < combinationStrengths.length(); j++) {
                combinationStrengths.set(j, vectorRand.nextDouble());
            }
            combinationStrengths.divide(combinationStrengths.elementSum());
            FragmentedNeuralQueue currQueue = primaryQueue.copy();
            for (int k = 0; k < combinationStrengths.length(); k++) {
                currQueue.basicInterpolate(queuePopulation.get(k),
                        combinationStrengths.get(k) * interpolationMagnitude);
            }
            LogTimer.endLog();
            autoencoder.setQueue(currQueue);
            refreshNetworkState(autoencoder, autoencoderConnectomePath);
            decodeToSequence(autoencoder, outputSequence, decoderInputSequence);
        }

        writeLeadsheetFile(outputSequence, outputFilePath, "_randomInterpSamples", songTitle);

    } else {
        throw new RuntimeException("Given queue folder is not a directory!");
    }
}

From source file:org.opensha.commons.util.DataUtils.java

/**
 * Creates an array of random {@code double} values.
 * @param length of output array/*  w ww  .  jav a 2s  . com*/
 * @return the array of random {@code double}s
 */
public static double[] randomValues(int length) {
    Random random = new Random();
    double[] values = new double[length];
    for (int i = 0; i < length; i++) {
        values[i] = random.nextDouble();
    }
    return values;
}

From source file:org.diorite.utils.math.DioriteRandomUtils.java

public static double getRandomDouble(final Random random, final double min, final double max)
        throws IllegalArgumentException {
    if (Double.compare(min, max) == 0) {
        return max;
    }/*from ww w.  ja  v a  2 s.c o m*/
    Validate.isTrue(max > min, "Max can't be smaller than min!");
    return (random.nextDouble() * (max - min)) + min;
}

From source file:com.linkedin.pinot.query.aggregation.groupby.NoDictionaryGroupKeyGeneratorTest.java

/**
 * Helper method to build a segment as follows:
 * <ul>/* w  ww . jav  a  2  s .co  m*/
 *   <li> One string column without dictionary. </li>
 *   <li> One integer column with dictionary. </li>
 * </ul>
 *
 * It also computes the unique group keys while it generates the index.
 *
 * @return Set containing unique group keys from the created segment.
 *
 * @throws Exception
 */
private static RecordReader buildSegment() throws Exception {
    Schema schema = new Schema();

    for (int i = 0; i < COLUMN_NAMES.length; i++) {
        DimensionFieldSpec dimensionFieldSpec = new DimensionFieldSpec(COLUMN_NAMES[i], DATA_TYPES[i], true);
        schema.addField(dimensionFieldSpec);
    }

    SegmentGeneratorConfig config = new SegmentGeneratorConfig(schema);
    config.setRawIndexCreationColumns(Arrays.asList(NO_DICT_COLUMN_NAMES));

    config.setOutDir(INDEX_DIR_PATH);
    config.setSegmentName(SEGMENT_NAME);

    Random random = new Random();
    List<GenericRow> rows = new ArrayList<>(NUM_ROWS);
    for (int i = 0; i < NUM_ROWS; i++) {
        Map<String, Object> map = new HashMap<>(NUM_COLUMNS);

        for (FieldSpec fieldSpec : schema.getAllFieldSpecs()) {
            String column = fieldSpec.getName();

            FieldSpec.DataType dataType = fieldSpec.getDataType();
            switch (dataType) {
            case INT:
                map.put(column, random.nextInt());
                break;

            case LONG:
                map.put(column, random.nextLong());
                break;

            case FLOAT:
                map.put(column, random.nextFloat());
                break;

            case DOUBLE:
                map.put(column, random.nextDouble());
                break;

            case STRING:
                map.put(column, "value_" + i);
                break;

            default:
                throw new IllegalArgumentException("Illegal data type specified: " + dataType);
            }
        }

        GenericRow genericRow = new GenericRow();
        genericRow.init(map);
        rows.add(genericRow);
    }

    RecordReader recordReader = new GenericRowRecordReader(rows, schema);
    SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl();
    driver.init(config, recordReader);
    driver.build();

    return recordReader;
}

From source file:de.terministic.serein.core.genome.DoubleGenome.java

@Override
public Double getRandomValue(Random random) {
    return random.nextDouble();
}

From source file:org.ballerinalang.langserver.command.testgen.ValueSpaceGenerator.java

/**
 * Returns value space for a given BTypeSymbol.
 *
 * @param tSymbol  BTypeSymbol to evaluate
 * @param template templates to be modified
 * @return {@link String}  modified templates
 *///from   ww  w  .  j  a  va 2s  . c o m
public static String[] getValueSpaceByTypeSymbol(BTypeSymbol tSymbol, String[] template) {
    if (tSymbol == null) {
        String[] result = new String[] { "()" };
        populateValueSpace(result, template, () -> "()");
        return template;
    }
    Random random = new Random();
    switch (tSymbol.name.getValue()) {
    case "int":
    case "any":
        String[] resultInt = new String[] { "-1", "0", "1" };
        populateValueSpace(resultInt, template, () -> String.valueOf(random.nextInt((template.length))));
        break;
    case "string":
        String[] resultStr = new String[] { "\"\"", "\"foo\"", "\"bar\"" };
        populateValueSpace(resultStr, template,
                () -> "\"" + RandomStringUtils.randomAlphabetic(RANDOM_WORDS_LENGTH) + "\"");
        break;
    case "float":
        String[] resultFloat = new String[] { "-1.0", "0.0", "1.0" };
        populateValueSpace(resultFloat, template, () -> String.format("%.1f", random.nextDouble()));
        break;
    case "json":
        String[] resultJson = new String[] { "{\"key\": \"value\"}", "{}", "{\"foo\": \"bar\"}" };
        populateValueSpace(resultJson, template, () -> {
            String key = RandomStringUtils.randomAlphabetic(RANDOM_WORDS_LENGTH);
            String value = RandomStringUtils.randomAlphabetic(RANDOM_WORDS_LENGTH);
            return "{\"" + key + "\": \"" + value + "\"}";
        });
        break;
    case "boolean":
        String[] resultBool = new String[] { "false", "true" };
        populateValueSpace(resultBool, template, () -> String.valueOf(random.nextBoolean()));
        break;
    case "xml":
        String[] resultXml = new String[] { "xml `<msg>hello</msg>`", "xml `<foo>bar</foo>`",
                "xml `<bar>foo</bar>`" };
        populateValueSpace(resultXml, template, () -> {
            String key = RandomStringUtils.randomAlphabetic(RANDOM_WORDS_LENGTH);
            String value = RandomStringUtils.randomAlphabetic(RANDOM_WORDS_LENGTH);
            return "xml `<" + key + ">" + value + "</" + key + ">`";
        });
        break;
    case "byte":
        String[] resultBlob = new String[] { "0" };
        populateValueSpace(resultBlob, template, () -> String.valueOf("0"));
        break;
    default:
        String[] result = new String[] { "()" };
        populateValueSpace(result, template, () -> "()");
        break;
    }
    return template;
}

From source file:com.facebook.LinkBench.distributions.GeometricDistribution.java

@Override
public long choose(Random rng) {
    return quantile(rng.nextDouble());
}

From source file:org.optaplanner.core.impl.heuristic.selector.common.nearby.BetaDistributionNearbyRandom.java

@Override
public int nextInt(Random random, int nearbySize) {
    double d = betaDistribution.inverseCumulativeProbability(random.nextDouble());
    int next = (int) (d * (double) nearbySize);
    // The method inverseCumulativeProbability() might return 1.0
    if (next >= nearbySize) {
        next = nearbySize - 1;/*from   w  w w.  j  a v  a2 s  . c o  m*/
    }
    return next;
}

From source file:Gpw.java

public static String generate(int pwl) {
    int c1, c2, c3;
    long sum = 0;
    int nchar;//from w  w w.j  av  a2  s .  c o  m
    long ranno;
    double pik;
    StringBuilder password;
    Random ran = new Random(); // new random source seeded by clock

    password = new StringBuilder(pwl);
    pik = ran.nextDouble(); // random number [0,1]
    ranno = (long) (pik * data.getSigma()); // weight by sum of frequencies
    sum = 0;
    for (c1 = 0; c1 < 26; c1++) {
        for (c2 = 0; c2 < 26; c2++) {
            for (c3 = 0; c3 < 26; c3++) {
                sum += data.get(c1, c2, c3);
                if (sum > ranno) {
                    password.append(alphabet.charAt(c1));
                    password.append(alphabet.charAt(c2));
                    password.append(alphabet.charAt(c3));
                    c1 = 26; // Found start. Break all 3 loops.
                    c2 = 26;
                    c3 = 26;
                } // if sum
            } // for c3
        } // for c2
    } // for c1

    // Now do a random walk.
    nchar = 3;
    while (nchar < pwl) {
        c1 = alphabet.indexOf(password.charAt(nchar - 2));
        c2 = alphabet.indexOf(password.charAt(nchar - 1));
        sum = 0;
        for (c3 = 0; c3 < 26; c3++)
            sum += data.get(c1, c2, c3);
        if (sum == 0) {
            break; // exit while loop
        }
        pik = ran.nextDouble();
        ranno = (long) (pik * sum);
        sum = 0;
        for (c3 = 0; c3 < 26; c3++) {
            sum += data.get(c1, c2, c3);
            if (sum > ranno) {
                password.append(alphabet.charAt(c3));
                c3 = 26; // break for loop
            } // if sum
        } // for c3
        nchar++;
    } // while nchar
    return password.toString();
}