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:Main.java

public static void main(String[] args) {
    Random random = new Random();
    for (int i = 0; i < 1000000000; i++) {
        float f = random.nextFloat() * 2 - 1;
        if (Float.isNaN(f)) {
            System.out.println("NaN!");
        }//from  ww  w .  jav a  2s  .  c  om
    }
}

From source file:Main.java

public static void main(String args[]) {

    Random randomno = new Random();

    // check next float value  
    System.out.println("Next float value: " + randomno.nextFloat());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    Random rand = new Random();

    boolean b = rand.nextBoolean();
    long l = rand.nextLong();
    float f = rand.nextFloat(); // 0.0 <= f < 1.0
    double d = rand.nextDouble(); // 0.0 <= d < 1.0
}

From source file:pro.foundev.GzipCompressionOfColumnExample.java

public static void main(String[] args) {
    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    try {/*from  ww w.  j av  a2s . c  o  m*/
        String inputText = "";
        Random random = new Random();
        for (int i = 0; i < 1000; i++) {
            String randomString = String.valueOf(random.nextFloat());
            String paddedRandomString = Strings.padEnd(randomString, 10, 'a');
            inputText += paddedRandomString + "\n";
        }
        Session session = cluster.newSession();
        session.execute("create keyspace if not exists test with replication ="
                + " { 'class':'SimpleStrategy', 'replication_factor':1 } ");
        session.execute("create table if not exists test.blobs (id int, value blob, primary key(id))");
        ByteBuffer zippedBlob = toByteBuffer(inputText);
        session.execute("insert into test.blobs (id, value) values (1, ?)", zippedBlob);
        Row row = session.execute("select * from test.blobs where id = 1 ").one();

        ByteBuffer fromCassandra = row.getBytes("value");
        String outputText = fromByteBuffer(fromCassandra);

        if (outputText.length() > 0) {
            System.out.println("output text is as follows");
            System.out.println(outputText);
        } else {
            System.out.println("no data in value from database FAILURE!!!");
        }
        if (inputText.equals(outputText)) {
            System.out.println("input text matches output text");
        } else {
            System.exit(188);
            System.out.println("critical error text does not match FAILURE!!!");
        }
    } finally {
        cluster.close();
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.QueryGenNMSLIB.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption(CommonParams.QUERY_FILE_PARAM, null, true, CommonParams.QUERY_FILE_DESC);
    options.addOption(CommonParams.MEMINDEX_PARAM, null, true, CommonParams.MEMINDEX_DESC);
    options.addOption(CommonParams.KNN_QUERIES_PARAM, null, true, CommonParams.KNN_QUERIES_DESC);
    options.addOption(CommonParams.NMSLIB_FIELDS_PARAM, null, true, CommonParams.NMSLIB_FIELDS_DESC);
    options.addOption(CommonParams.MAX_NUM_QUERY_PARAM, null, true, CommonParams.MAX_NUM_QUERY_DESC);
    options.addOption(CommonParams.SEL_PROB_PARAM, null, true, CommonParams.SEL_PROB_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    BufferedWriter knnQueries = null;

    int maxNumQuery = Integer.MAX_VALUE;

    Float selProb = null;//from   w w w . j a va2 s .c om

    try {
        CommandLine cmd = parser.parse(options, args);
        String queryFile = null;

        if (cmd.hasOption(CommonParams.QUERY_FILE_PARAM)) {
            queryFile = cmd.getOptionValue(CommonParams.QUERY_FILE_PARAM);
        } else {
            Usage("Specify 'query file'", options);
        }

        String knnQueriesFile = cmd.getOptionValue(CommonParams.KNN_QUERIES_PARAM);

        if (null == knnQueriesFile)
            Usage("Specify '" + CommonParams.KNN_QUERIES_DESC + "'", options);

        String tmpn = cmd.getOptionValue(CommonParams.MAX_NUM_QUERY_PARAM);
        if (tmpn != null) {
            try {
                maxNumQuery = Integer.parseInt(tmpn);
            } catch (NumberFormatException e) {
                Usage("Maximum number of queries isn't integer: '" + tmpn + "'", options);
            }
        }

        String tmps = cmd.getOptionValue(CommonParams.NMSLIB_FIELDS_PARAM);
        if (null == tmps)
            Usage("Specify '" + CommonParams.NMSLIB_FIELDS_DESC + "'", options);
        String nmslibFieldList[] = tmps.split(",");

        knnQueries = new BufferedWriter(new FileWriter(knnQueriesFile));
        knnQueries.write("isQueryFile=1");
        knnQueries.newLine();
        knnQueries.newLine();

        String memIndexPref = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM);

        if (null == memIndexPref) {
            Usage("Specify '" + CommonParams.MEMINDEX_DESC + "'", options);
        }

        String tmpf = cmd.getOptionValue(CommonParams.SEL_PROB_PARAM);

        if (tmpf != null) {
            try {
                selProb = Float.parseFloat(tmpf);
            } catch (NumberFormatException e) {
                Usage("A selection probability isn't a number in the range (0,1)'" + tmpf + "'", options);
            }
            if (selProb < Float.MIN_NORMAL || selProb + Float.MIN_NORMAL >= 1)
                Usage("A selection probability isn't a number in the range (0,1)'" + tmpf + "'", options);
        }

        BufferedReader inpText = new BufferedReader(
                new InputStreamReader(CompressUtils.createInputStream(queryFile)));

        String docText = XmlHelper.readNextXMLIndexEntry(inpText);

        NmslibQueryGenerator queryGen = new NmslibQueryGenerator(nmslibFieldList, memIndexPref);

        Random rnd = new Random();

        for (int docNum = 1; docNum <= maxNumQuery
                && docText != null; ++docNum, docText = XmlHelper.readNextXMLIndexEntry(inpText)) {
            if (selProb != null) {
                if (rnd.nextFloat() > selProb)
                    continue;
            }

            Map<String, String> docFields = null;

            try {
                docFields = XmlHelper.parseXMLIndexEntry(docText);

                String queryObjStr = queryGen.getStrObjForKNNService(docFields);

                knnQueries.append(queryObjStr);
                knnQueries.newLine();
            } catch (SAXException e) {
                System.err.println("Parsing error, offending DOC:" + NL + docText + " doc # " + docNum);
                throw new Exception("Parsing error.");
            }
        }

        knnQueries.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
        if (null != knnQueries)
            try {
                knnQueries.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        try {
            if (knnQueries != null)
                knnQueries.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        System.exit(1);
    }

    System.out.println("Terminated successfully!");
}

From source file:MathOps.java

public static void main(String[] args) {
    // Create a random number generator,
    // seeds with current time by default:

    Random rand = new Random();

    int i, j, k;//from   ww  w. j  a  v  a2s .  co m

    // Choose value from 1 to 100:

    j = rand.nextInt(100) + 1;

    k = rand.nextInt(100) + 1;

    printInt("j", j);
    printInt("k", k);

    i = j + k;
    printInt("j + k", i);

    i = j - k;
    printInt("j - k", i);

    i = k / j;
    printInt("k / j", i);

    i = k * j;
    printInt("k * j", i);

    i = k % j;
    printInt("k % j", i);

    j %= k;
    printInt("j %= k", j);

    // Floating-point number tests:

    float u, v, w; // applies to doubles, too

    v = rand.nextFloat();

    w = rand.nextFloat();

    printFloat("v", v);
    printFloat("w", w);

    u = v + w;
    printFloat("v + w", u);

    u = v - w;
    printFloat("v - w", u);

    u = v * w;
    printFloat("v * w", u);

    u = v / w;
    printFloat("v / w", u);

    // the following also works for

    // char, byte, short, int, long,

    // and double:

    u += v;
    printFloat("u += v", u);

    u -= v;
    printFloat("u -= v", u);

    u *= v;
    printFloat("u *= v", u);

    u /= v;
    printFloat("u /= v", u);

}

From source file:Main.java

public static void main(String[] args) {
    Random r = new Random();

    // generate some random boolean values
    boolean[] booleans = new boolean[10];
    for (int i = 0; i < booleans.length; i++) {
        booleans[i] = r.nextBoolean();//from   ww w  . jav a2  s. c o  m
    }

    for (boolean b : booleans) {
        System.out.print(b + ", ");
    }

    // generate a uniformly distributed int random numbers
    int[] integers = new int[10];
    for (int i = 0; i < integers.length; i++) {
        integers[i] = r.nextInt();
    }

    for (int i : integers) {
        System.out.print(i + ", ");
    }

    // generate a uniformly distributed float random numbers
    float[] floats = new float[10];
    for (int i = 0; i < floats.length; i++) {
        floats[i] = r.nextFloat();
    }

    for (float f : floats) {
        System.out.print(f + ", ");
    }

    // generate a Gaussian normally distributed random numbers
    double[] gaussians = new double[10];
    for (int i = 0; i < gaussians.length; i++) {
        gaussians[i] = r.nextGaussian();
    }

    for (double d : gaussians) {
        System.out.print(d + ", ");
    }
}

From source file:ffx.numerics.fft.Real3DCuda.java

/**
 * <p>//from w  ww  .  j av  a2  s  .  c  o m
 * main</p>
 *
 * @param args an array of {@link java.lang.String} objects.
 * @throws java.lang.Exception if any.
 */
public static void main(String[] args) throws Exception {
    int dimNotFinal = 64;
    int reps = 10;
    if (args != null) {
        try {
            dimNotFinal = Integer.parseInt(args[0]);
            if (dimNotFinal < 1) {
                dimNotFinal = 64;
            }
            reps = Integer.parseInt(args[1]);
            if (reps < 1) {
                reps = 5;
            }
        } catch (Exception e) {
        }
    }
    if (dimNotFinal % 2 != 0) {
        dimNotFinal++;
    }
    final int dim = dimNotFinal;
    System.out.println(String.format(
            "Initializing a %d cubed grid.\n" + "The best timing out of %d repititions will be used.", dim,
            reps));

    final int dimCubed = dim * dim * dim;
    final int dimCubed2 = (dim + 2) * dim * dim;

    /**
     * Create an array to save the initial input and result.
     */
    final double orig[] = new double[dimCubed2];
    final double answer[] = new double[dimCubed2];
    final double data[] = new double[dimCubed2];
    final double recip[] = new double[dimCubed];

    final float origf[] = new float[dimCubed2];
    final float dataf[] = new float[dimCubed2];
    final float recipf[] = new float[dimCubed];

    Random randomNumberGenerator = new Random(1);
    int index = 0;
    int index2 = 0;

    /**
     * Row-major order.
     */
    for (int x = 0; x < dim; x++) {
        for (int y = 0; y < dim; y++) {
            for (int z = 0; z < dim; z++) {
                float randomNumber = randomNumberGenerator.nextFloat();
                orig[index] = randomNumber;
                origf[index] = randomNumber;
                index++;

                recip[index2] = 1.0;
                recipf[index2] = 1.0f;
                index2++;
            }
            // Padding
            index += 2;
        }
    }

    Real3D real3D = new Real3D(dim, dim, dim);
    Real3DParallel real3DParallel = new Real3DParallel(dim, dim, dim, new ParallelTeam(),
            IntegerSchedule.fixed());
    Real3DCuda real3DCUDA = new Real3DCuda(dim, dim, dim, dataf, recipf);

    Thread cudaThread = new Thread(real3DCUDA);
    cudaThread.setPriority(Thread.MAX_PRIORITY);
    cudaThread.start();

    double toSeconds = 0.000000001;
    long parTime = Long.MAX_VALUE;
    long seqTime = Long.MAX_VALUE;
    long clTime = Long.MAX_VALUE;

    real3D.setRecip(recip);
    for (int i = 0; i < reps; i++) {
        System.arraycopy(orig, 0, data, 0, dimCubed2);
        long time = System.nanoTime();
        real3D.convolution(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format("%2d Sequential: %8.3f", i + 1, toSeconds * time));
        if (time < seqTime) {
            seqTime = time;
        }
    }
    System.arraycopy(data, 0, answer, 0, dimCubed2);

    real3DParallel.setRecip(recip);
    for (int i = 0; i < reps; i++) {
        System.arraycopy(orig, 0, data, 0, dimCubed2);
        long time = System.nanoTime();
        real3DParallel.convolution(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format("%2d Parallel:   %8.3f", i + 1, toSeconds * time));
        if (time < parTime) {
            parTime = time;
        }
    }
    double maxError = Double.MIN_VALUE;
    double rmse = 0.0;
    index = 0;
    for (int x = 0; x < dim; x++) {
        for (int y = 0; y < dim; y++) {
            for (int z = 0; z < dim; z++) {
                double error = Math.abs((orig[index] - data[index] / dimCubed));
                if (error > maxError) {
                    maxError = error;
                }
                rmse += error * error;
                index++;
            }
            index += 2;
        }
    }
    rmse /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format("Parallel RMSE:   %12.10f, Max: %12.10f", rmse, maxError));

    for (int i = 0; i < reps; i++) {
        System.arraycopy(origf, 0, dataf, 0, dimCubed2);
        long time = System.nanoTime();
        real3DCUDA.convolution(dataf);
        time = (System.nanoTime() - time);
        System.out.println(String.format("%2d CUDA:     %8.3f", i + 1, toSeconds * time));
        if (time < clTime) {
            clTime = time;
        }
    }
    real3DCUDA.free();
    real3DCUDA = null;

    maxError = Double.MIN_VALUE;
    double avg = 0.0;
    rmse = 0.0;
    index = 0;
    for (int x = 0; x < dim; x++) {
        for (int y = 0; y < dim; y++) {
            for (int z = 0; z < dim; z++) {
                if (Float.isNaN(dataf[index])) {
                    logger.info(String.format("Not a number %d %d %d", x, y, z));
                    System.exit(-1);
                }
                double error = Math.abs(origf[index] - dataf[index]);
                avg += error;
                if (error > maxError) {
                    maxError = error;
                }
                rmse += error * error;
                index++;
            }
            index += 2;
        }
    }
    rmse /= dimCubed;
    avg /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format("CUDA RMSE:   %12.10f, Max: %12.10f, Avg: %12.10f", rmse, maxError, avg));

    System.out.println(String.format("Best Sequential Time:  %8.3f", toSeconds * seqTime));
    System.out.println(String.format("Best Parallel Time:    %8.3f", toSeconds * parTime));
    System.out.println(String.format("Best CUDA Time:        %8.3f", toSeconds * clTime));
    System.out.println(String.format("Parallel Speedup: %15.5f", (double) seqTime / parTime));
    System.out.println(String.format("CUDA Speedup:     %15.5f", (double) seqTime / clTime));
}

From source file:org.bimserver.GeometryGenerator.java

public static void main(String[] args) {
    float maxDiff = 0.1f;

    test1(maxDiff);// w  w  w. j a v a 2  s  .  c o  m
    test2(maxDiff);

    Random random = new Random();
    for (int i = 0; i < 10; i++) {
        float[] matrix = new float[16];
        Matrix.setIdentityM(matrix, 0);
        for (int j = 0; j < 10; j++) {
            Matrix.rotateM(matrix, 0, random.nextFloat() * 360, random.nextFloat(), random.nextFloat(),
                    random.nextFloat());
        }

        float[] v1 = new float[] { random.nextFloat(), random.nextFloat(), random.nextFloat(), 1 };
        float[] v2 = new float[] { random.nextFloat(), random.nextFloat(), random.nextFloat(), 1 };
        float[] v3 = new float[] { random.nextFloat(), random.nextFloat(), random.nextFloat(), 1 };
        float[] r1 = new float[4];
        float[] r2 = new float[4];
        float[] r3 = new float[4];
        Matrix.multiplyMV(r1, 0, matrix, 0, v1, 0);
        Matrix.multiplyMV(r2, 0, matrix, 0, v2, 0);
        Matrix.multiplyMV(r3, 0, matrix, 0, v3, 0);

        float[] calculatedMatrix = getTransformationMatrix(v1, v2, v3, r1, r2, r3, maxDiff);

        test(v1, r1, calculatedMatrix, maxDiff);
        test(v2, r2, calculatedMatrix, maxDiff);
        test(v3, r3, calculatedMatrix, maxDiff);

        for (int j = 0; j < 10; j++) {
            float[] q1 = new float[] { random.nextFloat(), random.nextFloat(), random.nextFloat(), 1 };
            float[] q2 = new float[] { random.nextFloat(), random.nextFloat(), random.nextFloat(), 1 };
            float[] q3 = new float[] { random.nextFloat(), random.nextFloat(), random.nextFloat(), 1 };
            float[] b1 = new float[4];
            float[] b2 = new float[4];
            float[] b3 = new float[4];
            Matrix.multiplyMV(b1, 0, matrix, 0, q1, 0);
            Matrix.multiplyMV(b2, 0, matrix, 0, q2, 0);
            Matrix.multiplyMV(b3, 0, matrix, 0, q3, 0);

            test(q1, b1, calculatedMatrix, maxDiff);
            test(q2, b2, calculatedMatrix, maxDiff);
            test(q3, b3, calculatedMatrix, maxDiff);
        }
    }
}

From source file:Main.java

public static float nextFloat(int lower, int upper) {
    Random ra = new Random();
    int n = lower + ra.nextInt(upper - lower);
    float m = ra.nextFloat();
    return n + m;
}