java.util.Random: nextInt vs nextDouble

Hi,

I am using java.util.Random to generate a value between -180 and +180; I only get a proper value when I use nextDouble. Using nextInt I get values that are not within the range I specified. Here is my code:

private Random randomize =new Random();

privateint upperLimit = 180;

privateint lowerLimit = -180;

privateint wD;

(...)

wD = (randomize.nextInt() * (upperLimit - lowerLimit) + lowerLimit);

... gives me a value of e.g. 140642644; when I change the variables to double as well as to (int) randomize.nextDouble()... I get a correct value between -180 and +180.

Why?

[902 byte] By [SFLa] at [2007-11-26 18:09:06]
# 1
The value of nextInt() is not between 0 and 1 (logically, because it's an int), but can be any valid int value in the range from Integer.MIN_VALUE to Integer.MAX_VALUE.
quittea at 2007-7-9 5:40:58 > top of Java-index,Java Essentials,Java Programming...
# 2
nextInt(361) - 180(Double check it for OBOEs.)
jverda at 2007-7-9 5:40:58 > top of Java-index,Java Essentials,Java Programming...
# 3

new java.util.Random().nextDouble() returns values 0.0 to just less than 1.0 (imagine 0.9999999999 or whatever is just less than one)

on the other hand new java.util.Random().nextInt() return uniformly distributed int values from the random number generator's sequence. the implementation of nextInt() is

public int nextInt() { return next(32); }

so the range of returned values will be something like:

147137735

870850416

447241877

-89082765

cheers

JohnAJohna at 2007-7-9 5:40:58 > top of Java-index,Java Essentials,Java Programming...