Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

Java - 4 different ways to generate random double

0 contributions
2 points

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

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more