Languages
[Edit]
EN

Java - 4 different ways to generate random double

2 points
Created by:
Brett4
465

1. Generate random double with ThreadLocalRandom

public static double nextDouble() {
    return ThreadLocalRandom.current().nextDouble();
}

Example:

System.out.println(nextDouble()); // 0.6260248581412109
System.out.println(nextDouble()); // 0.8624217725537807
System.out.println(nextDouble()); // 0.4870344165107542


2. Generate random double with Random

public static double nextDouble2() {
    return new Random().nextDouble();
}

Example:

System.out.println(nextDouble2()); // 0.8853243052768429
System.out.println(nextDouble2()); // 0.763297548370907
System.out.println(nextDouble2()); // 0.8125479078816122


3. Generate random double with Math

public static double nextDouble3() {
    return Math.random();
}

Example:

System.out.println(nextDouble3()); // 0.36225288271248024
System.out.println(nextDouble3()); // 0.03675822890573344
System.out.println(nextDouble3()); // 0.48065002903809895


4. Generate random double with Random and DoubleStream

public static double nextDouble4() {
    // java 8 + DoubleStream
    return new Random().doubles().limit(1).findFirst().getAsDouble();
}

Example:

System.out.println(nextDouble4()); // 0.9310238127103216
System.out.println(nextDouble4()); // 0.7304200864872137
System.out.println(nextDouble4()); // 0.9112523320636519


References

ThreadLocalRandom - Java docs
Math - Java docs
Random - Java docs
DoubleStream - Java docs

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - random numbers

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join