0

I want to generate some random doubles and add them into an ArrayList, but it seems that the nextDouble() function returns a unique double every time, not a new one

Random r = new Random(); ArrayList<Pair> centers = new ArrayList<Pair>(); ArrayList<ArrayList<Pair>> classes = new ArrayList<ArrayList<Pair>>(); for (int i=0 ; i < 100; i++) { // Random r = new Random (); // System.out.println (r.nextDouble ()) ; double a = r.nextDouble () * 10; double b = r.nextDouble () * 10; centers.add (new Pair (a, b )); System.out.println (centers); } 

Can anyone help me with this? Is this a mistake of optimization?

10
  • What if you rewrite r = new Random(); after having calling it? Random r = new Random(); double a = r.nextDouble() * 10; r = new Random(); double b = r.nextDouble() * 10; Commented May 14, 2012 at 12:16
  • 3
    What do you mean with "not a new one"? nextDouble returns a unique double, just as it should.. Commented May 14, 2012 at 12:17
  • 1
    What do you mean when you say that nextDouble() returns a unique double and not a new one. Isn't that the same thing? (and the excpected behaviour) Commented May 14, 2012 at 12:18
  • If you want to reset the seed, you can do as sp00m wrote: double a = new Random().nextDouble * 10; etc. If you want to use a more than once, do double b = a;. Commented May 14, 2012 at 12:18
  • @Marcus: I want to have 100 different random generated numbers, but in this way, I get 100 numbers that all are equal Commented May 14, 2012 at 12:19

1 Answer 1

4

I ran this code:

public static void main(String[] args) { Random r = new Random(); ArrayList<Pair> centers = new ArrayList<Pair>(); for(int i = 0; i < 100; i++ ) { double a = r.nextDouble() * 10; double b = r.nextDouble() * 10; centers.add( new Pair(a, b) ); } System.out.println(centers); } 

This was the output:

[(8.08, 8.06), (9.97, 1.83), (3.83, 3.19), (2.97, 2.51), (9.40, 2.88), (7.78, 2.59), (1.67, 9.07) ... 

Isn't that what you want? FYI, this is the Pair class I used:

class Pair { private final double a, b; Pair(double a, double b) { this.a = a; this.b = b; } @Override public String toString() { return String.format("(%.2f, %.2f)", a, b); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.