Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Regarding radom number generation
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
mzhang




PostPosted: Thu Jul 21, 2005 12:33 am   Post subject: Regarding radom number generation

This is my first post in this forum, although I've been reading past threads, this serves as my useless introduction.

As for random numbers, I usually just do

code:

int randomNumber = Math.random() * myRange;

.

I realize that this causes loss of precision in the number as rounding gives less chance of recieving 0 and myRange.

Can anyone post a alternate solution to generate random numbers?
Sponsor
Sponsor
Sponsor
sponsor
[Gandalf]




PostPosted: Fri Jul 22, 2005 2:08 am   Post subject: (No subject)

Yep, what you gave gives an error because what is returned is actually a long. This method works much better:
Java:
int RandomNumber = (int) (Math.random() * 100) % (maxNumber-minNumber+1) + minNumber;

If you need any help with an explanation, just say so - the % is a modulo (or modulus, whatever) operator - right now I'm a tad sleepy...
You see? I'm already giving Java advice on my 2nd or 3rd day!
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 2 Posts ]
Jump to:   


Style:  
Search: