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!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Understanding Math.random

Will Dev
Ranch Hand
Posts: 31
Hi everybody

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.

Ranch Foreman
Posts: 2240
28
• 1
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
• 1
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
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.