• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Math.random()

 
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 612
7
Mac OS X Python
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
An another way to do this ..
(int) Math.ceil(Math.random() * 50)

------------------
Sateesh Donti
 
Steve Fahlbusch
Bartender
Posts: 612
7
Mac OS X Python
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).]
 
I wasn't selected to go to mars. This tiny ad got in ahead of me:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic