Gianmarco F. Gianmarco F. - 1 year ago 77
Java Question

Fastest way to generate a random double number in java

In a project in which I'm working for, I'm required to either generate n random

numbers (depending from what the input file says) or converting them to
if I have them from my input file. Those numbers should have only 2 decimals after the comma (ex.:

I know that in Java 8, there are 2 ways of doing this:

  1. Java 8 way:
    n_th number = Double.parseDouble(new DecimalFormat("#.##").format(ThreadLocalRandom.current().nextDouble(0,1)).replace(",","."));

  2. Old fashion way:
    n_th number = Double.parseDouble(new DecimalFormat("#.##").format(new Random().nextDouble()).replace(",", "."));

Asymptotically speaking, which is the fastest? From my poor knowledge of A.D.S., I'd say it would be the same time (
?) but I'm not 100% sure

Aside from these two ways, are there any other ways to generate random
which are faster, asymptotically speaking, than my proposals? (rather, are there methods that can do everything in

Thank you in advance to everyone who will spend a minute to answer to this question of mine

Answer Source

Both of your approaches use strings as an intermediate representation, this will be quite inefficient (memory allocation, string parsing, string formatting are all relatively slow operations. You probably also want to avoid allocating multiple instances of Random.

Given that you only want two decimal digits, why not create an integer in the range of 0..99 and divide it by 100.0?

Random random = new Random();  // Only one instance needed.
for (int n = 0; n < total; n++) {
   double nthRandomNumber = random.nextInt(100) / 100.0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download