Quote (silvermace @ Apr 8 2013 11:08pm)
Code
Random rand=new Random();
x=2*rand.nextDouble()-1;
rand.nextDouble() returns a value from [0, 1). So you'll never get the value 1, which means that you'll never get (2*rand.nextDouble()) == 2. therefore, you'll never get 1 which is why your interval is from [-1, 1)
I know, thanks.

I also know, as you have mentioned, that any randomly generated number is only pseudo-random (but equally distributed), but let's leave that aside.
Quote (silvermace @ Apr 8 2013 11:08pm)
Code
Random rand=new Random();
x=rand.nextDouble()-rand.nextDouble();
When you say that it's not equally distributed, what do you mean? .
I mean that not every number in (-1,1) has the same probability to be drawn with the second approach.
I'll explain with two dice:
rand.nextInt(6)+1 + rand.nextInt(6)+1 will give integers from [2,12], where some numbers, such as 7, aber more probable than others like 2 or 12. There are several outcomes that roll a 7, (3+4; 4+3; 5+2 etc.) but only one that rolls a 12 (6+6).
rand.nextInt(11)+2 will give Integers from [2,12], but they are equally distributed, meaning each number from 2 to 12 is drawn with the same probability.
So, rand.nextDouble()-rand.nextDouble() will give me a number from (-1,1), but I am not sure whether they are equally distributed.
Quote (silvermace @ Apr 8 2013 11:08pm)
Code
Random rand=new Random();
x=rand.nextDouble();
if(rand.nextBoolean()==true)
{
x=-x;
}
I'm pretty sure you're right about this one.
Which leaves the problem of 0 being twice as probable as any other number from (-1,1) with this approach.
Quote (carteblanche @ Apr 9 2013 01:01am)
can you explain what you're trying to accomplish?
I want to generate random numbers from the interval (-1,1), with the same probability for each number that can be drawn to be drawn. It's a programming exercise.
Another try:
Code
x=rand.nextDouble();
if(x==0 && rand.nextBoolean()==true)
{
while(x==0)
{
x=rand.nextDouble();
}
}
if(rand.nextBoolean()==true)
{
x=-x;
}
Idea: if it is 0, give it a 50% of not being zero.
This post was edited by tt_toby on Apr 9 2013 03:53am