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

`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:
`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 (
`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

``````Random random = new Random();  // Only one instance needed.