aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confusion in random() function Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Confusion in random() function" Watch "Confusion in random() function" New topic
Author

Confusion in random() function

Shivani Prajapati
Greenhorn

Joined: Aug 23, 2006
Posts: 9
What will be the result of the expression ((int) (Math.random()*4))

Answer in khalid mughal book is � �expression will evaluate to one of the numbers 0,1,2 or 3.�
But how can it be possible?
Paras Jain
Ranch Hand

Joined: Feb 26, 2005
Posts: 137
Hi,
As per the API random function "Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range."
That means you will get something between 0 and 1(non-inclusive) like 0.1, 0.2,.03 .... 0.999. Any number within this range when multiplied by 4 wil give values between 0 to 4 like
.1*4 = .4 ,
.6*4 = 2.4 .....
.999*4 = 3.996.

Hope you got the point.
Thanks
Paras


Paras Jain
SCJP 5.0
Paras Jain
Ranch Hand

Joined: Feb 26, 2005
Posts: 137
And I forgot to mention that when these numbers will be casted to (int) the values after decimal will be lost
.1*4 = .4 which becomes 0,
.6*4 = 2.4 which becomes 2.....
.999*4 = 3.996 which becomes 3
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Confusion in random() function
 
Similar Threads
How can I add error handling facilities to this code?
WA #1.....word association
Constructor Expression
Qn about boolean & operator
How do you like them apples?