wood burning stoves 2.0*
The moose likes Java in General and the fly likes Weird Random Number Failure Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Weird Random Number Failure" Watch "Weird Random Number Failure" New topic
Author

Weird Random Number Failure

Daniel Croft
Greenhorn

Joined: Feb 16, 2012
Posts: 21

So I'm trying to generate a random long, preferably in the full range between Long.MIN_VALUE and Long.MAX_VALUE. My first (very naive) attempt was "Long.MIN_VALUE + (long) (Math.Random() * (Long.MAX_VALUE - Long.MIN_VALUE + 1));", obviously this didn't work because the calculation overflowed. I eventually got lazy and decided to just use the positive numbers, so I tried "(long) Math.Random()*(Long.MAX_VALUE);" but for some reason this always returns 0. I'd really like to know why this doesn't work and I'd appreciate any ideas on how to accomplish my goal. I thought about using a BigInteger, but this code needs to be speedy. Thanks for your help.
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3606
    
  60

(long) Math.Random()*(Long.MAX_VALUE) will always return 0, because you first cast the Math.Random() to long, which strips off decimal digits from it and therefore always results in zero.

Have a look at the java.util.Random class. It can probably give you all you need.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37936
    
  22
Agree the java.util.Random class’ method is a better solution, but you can sort out that multiplication and cast if you remember that cast has a higher precedence than * and add one pair of () appropriately.
Daniel Croft
Greenhorn

Joined: Feb 16, 2012
Posts: 21

Wow, I can't believe I didn't see that. I guess that's what you get for coding in the middle of the night. Thanks guys
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37936
    
  22
You’re welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Weird Random Number Failure
 
Similar Threads
how to get the oldest timestamp record in an array list
Locking can't be that simple
B&S Is it OK To Generate The long Value For The Lock in "lockRecord()" Randomly?
Infinite for loop
Generate Cookie Value