Reputation: 800
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:
nthNumber = Double.parseDouble(new DecimalFormat("#.##").format(ThreadLocalRandom.current().nextDouble(0,1)).replace(",","."));
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
Upvotes: 4
Views: 11366
Reputation: 1596
Your code looks complicated.
Did you consider the following:
DecimalFormat decimalFormat = new DecimalFormat("0.00");
String twoDigitRandom = decimalFormat.format(Math.random());
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Edit: Added after the comment:
If you would like to control the number of digits and not to have a String as end result, then I would advise not to use Double, try BigDecimal instead:
MathContext m = new MathContext(3);
BigDecimal randomWithTwoDigits = new BigDecimal(Math.random(), m);
Upvotes: 2
Reputation: 18803
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;
}
Upvotes: 12