• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Understanding Math.random

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Rancher
Posts: 5008
38
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 79178
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic