This week's book giveaway is in the Agile forum.
We're giving away four copies of Head First Agile and have Andrew Stellman & Jennifer Greene on-line!
See this thread for details.
Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Understanding Math.random  RSS feed

 
Will Dev
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everybody

Could someone please help me understand the mathematical function (Math.random()* 10).

I understand it is a mathematical function that generates random numbers, but how does *10 limit the random numbers from 0 to 9. is it just something i must remember or is there a reason behind it.
 
Norm Radder
Ranch Foreman
Posts: 2240
28
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the random method returns a value from 0 to .99999
then multiplying that value by 10 gives a number in the range 0 to 9.9999 and truncating to int gives 0 to 9
multiplying by 100 gives 0 to 99.999 and truncation to int gives 0 to 99
 
Campbell Ritchie
Marshal
Posts: 55793
164
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't do arithmetic on Math#random. Create an instance of the Random class because it has many methods which are easier to use. Read their documentation carefully before you use them. You probably want myRandom.nextInt(10).
Note that Math#random uses a Random instance behind the scenes anyway.
 
Will Dev
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much for the help,

it was a math function i'v come across a few times and couldn't make sense of the *10 part.

Norm Radder that put it perfectly into perspective for me, thanks.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!