aspose file tools*
The moose likes Beginning Java and the fly likes Math.random() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Math.random()" Watch "Math.random()" New topic
Author

Math.random()

shree vijay
Ranch Hand

Joined: Sep 18, 2000
Posts: 208
Math.random() creates a random double between 0.0 to 1.0 (1.0 excluded).
Suppose i want to generate numbers between 1 and 50 (both inclusive),

(int)Math.round(Math.random()*50)
is the expression i will use. Will the expression definitely create 50?
If the result of random() is 0.99... and it is multiplied by 50, and then if the round() creates a 50, then it is fine.
I can understand this, but i would like somebody to confirm.
Shree


Regards,<BR>Shree
Steve Fahlbusch
Bartender

Joined: Sep 18, 2000
Posts: 559
    
    7

>Math.random() creates a random double between 0.0 to 1.0 (1.0 >excluded). << correct<br /> >Suppose i want to generate numbers between 1 and 50 (both >inclusive),
>(int)Math.round(Math.random()*50)
will create uniform random numbers in the range of
0 to 50 (with 1/100 probability of being 0 or 50 and
1/50 probability of being ( 1, 2, 3, 4, ... or 49 ).
>is the expression i will use.
i would use
1 + (int) ( Math.random() * 50 )
which Math.random() yeilds a number 0.0 to 0.99999
* 50 yeilds 0.0 to 49.99999
(int) yeilds 0 to 49
1 + yeilds 1 to 50
sateesh donti
Greenhorn

Joined: Sep 25, 2000
Posts: 2
Hi,
An another way to do this ..
(int) Math.ceil(Math.random() * 50)

------------------
Sateesh Donti


Sateesh Donti
Steve Fahlbusch
Bartender

Joined: Sep 18, 2000
Posts: 559
    
    7

Yes that will work execpt in the case random() returns 0.0
Which it appears that it never does.

[This message has been edited by Steve Fahlbusch (edited September 26, 2000).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Math.random()