Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 double numbers (depending from what the input file says) or converting them to doubles if I have them from my input file. Those numbers should have only 2 decimals after the comma (ex.: 0.98).

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

  1. Java 8 way: nthNumber = Double.parseDouble(new DecimalFormat("#.##").format(ThreadLocalRandom.current().nextDouble(0,1)).replace(",","."));
  2. Old fashion way: nthNumber = 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 (O(n)?) but I'm not 100% sure

Aside from these two ways, are there any other ways to generate random doubles between 0 and 1 which are faster, asymptotically speaking, than my proposals? (rather, are there methods that can do everything in O(n) or O(1) ?)

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

like image 888
Gianmarco F. Avatar asked Sep 19 '25 02:09

Gianmarco F.


1 Answers

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;
}
like image 80
Stefan Haustein Avatar answered Sep 20 '25 14:09

Stefan Haustein