Emir Peskovic
Emir Peskovic

Reputation: 37

Math.random() in Java, how is this possible?

Currently in class, learning about math in Java

I got speechless when my teacher showed me this formula?

if ((int)(Math.random() * 15) == 1) { 

How can something * 15 be 1?

Upvotes: 1

Views: 524

Answers (3)

CarefreeCrayon
CarefreeCrayon

Reputation: 249

This is because of the cast to integer

(int) Math.random()

You see Math.random() gives a random number between 0.0 and 1.0 when you cast to an integer you are effectively saying - " Throw out all the decimal places"

So if you had 0.5 doing (int) Math.random() would give you 0.

Now looking at your code, you'd have something like this

Assuming Math.random() gives 0.3, you'd have

((int)(0.3 * 15) == 1) which will be ((int)(4.5) == 1) now remember what casting to int does? throw out the decimal places. So we are left with if (4 == 1).

In this case the condition will be false so the code in the if won't run but there is a chance that you would have a number like 1.xx after multiplying.

Upvotes: 1

Man Programmer
Man Programmer

Reputation: 5356

Suppose Math.random returns 0.08907633950002491

Now according to your formula

0.08907633950002491*15 it returns 1.3361450925003737

after int type cast it will be 1

(int)(Math.random() * 15) == 1 returns true

Upvotes: 3

Thamiar
Thamiar

Reputation: 610

The java.lang.Math.random() returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

x * 15 = 1

x = 1/15

So X is a double value from interval 0-1. Everything is correct.

Upvotes: 1

Related Questions