Languages
[Edit]
EN

Java - 4 different ways to generate random double

2 points
Created by:
Marcin
2462

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

Java - random numbers

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.