This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Math.random()

 
shree vijay
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Steve Fahlbusch
Bartender
Posts: 602
7
Mac OS X Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
An another way to do this ..
(int) Math.ceil(Math.random() * 50)

------------------
Sateesh Donti
 
Steve Fahlbusch
Bartender
Posts: 602
7
Mac OS X Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic