File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generalized formula for producing numbers from Math.random()?

 
Hassan Naqvi
Ranch Hand
Posts: 158
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends,
Is there any Generalized Formula for producing numbers from Math.random().
For example, generate numbers from 3 to 8 by using Math.random()
Regards,
Hassan.
 
Trevor Green
Ranch Hand
Posts: 44
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You mean like:
(int)((Math.random() * 5)+2)
 
Dave Vick
Ranch Hand
Posts: 3244
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Trevor
I think you want to add 3 to it to get a number from 3 to 8 because random return a number >= 0 and <1.
Dave
 
Trevor Green
Ranch Hand
Posts: 44
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yep, quite right. Maths let me down there.
The key concept is (int)2.999999 = 2.
Casting to an int always rounds down.
 
Hassan Naqvi
Ranch Hand
Posts: 158
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Trevor & Dave.
I mean, can we make a generalized formula for generating numbers with our rquired range.Something like this.
(int)(Math.random() * lower limit )+ upper limit..
where lower limit is in my first post is 3 & upper limit is 8.
That is have a generalized formula in which i have to just put lower & upper limts.
Regards,
Hassan.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic