shree vijay

Ranch Hand

Posts: 208

posted 16 years ago

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

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

Regards,<BR>Shree

posted 16 years ago

>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

>(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

sateesh donti

Greenhorn

Posts: 2