# Thread: generating double random number between 0 and 1

1. Member
Join Date
Dec 2009
Posts
59
Rep Power
0

## generating double random number between 0 and 1

hello
can somebody tell me how to generate double random number between 0 and 1
I have used the following but it gives me an error
random.nextDouble(1.0)

thanks

2. Member
Join Date
Mar 2010
Posts
88
Rep Power
0
Java Code:
```import java.util.Random;

Random r = new Random();
double zeroToOne = r.nextInt(1001) / 1000```

3. Senior Member
Join Date
Feb 2010
Location
Ljubljana, Slovenia
Posts
470
Rep Power
5
Please don't open duplicate threads. To answer your question, the most simple way would be
Java Code:
`double d = Math.random();`

4. Member
Join Date
Dec 2009
Posts
59
Rep Power
0
sorry I didn't duplicate it may be there is an error
I found that random.nextDouble() it self gives random number between 0 and 1
thanks alot

5. Originally Posted by Cruncher
Java Code:
```import java.util.Random;

Random r = new Random();
double zeroToOne = r.nextInt(1001) / 1000```

But seriously Cruncher, please test your advice before giving it if possible. For example here's my test of your recommendation:
Java Code:
```import java.util.Random;

public class RandomFo {
public static void main(String[] args) {
Random r = new Random();

for (int i = 0; i < 40; i++) {
double zeroToOne = r.nextInt(1001) / 1000;
System.out.println(zeroToOne);
}
}
}```
Run this and tell me what you see.

(to the OP, please ignore Cruncher's reply and go with Moon's).
Last edited by Fubarable; 04-17-2010 at 09:00 PM.

6. Member
Join Date
Mar 2010
Posts
88
Rep Power
0
sorry divide it by 1000.0 then it will recognize as a double. for got that java says int/int = int

7. Originally Posted by Cruncher
sorry divide it by 1000.0 then it will recognize as a double. for got that java says int/int = int
Even that's a bad idea as it results in a "grainier" randomization (and thus less random) than is possible with either Moon's recommendation or the OP's final choice. It's much better to go with the methods already available in the API for creating random doubles than what you've suggested, even with the modification.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•