Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Casting Math.random?

Had a look around the questions on this site and could not quite find the answer I was looking for about type casting the Math.random() method from double to int. My question is, why does Math.random only return a 0 without parentheses whereas it returns random numbers when it is contained within the parentheses? The first part of code returns 0:

int number; 
number = (int) Math.random() * 10; 
System.out.println("\nThe random number is " + number);

This code works however:

int number; 
number = (int) (Math.random() * 10); 
System.out.println("\nThe random number is " + number);

It should be noted I have seen a few different pieces of code on typecasting whereby some programmers seem to use both ways of casting.

like image 267
wilbomc Avatar asked Feb 13 '23 12:02

wilbomc


2 Answers

This code:

number = (int) Math.random() * 10; 

first calculates this:

(int) Math.random()

Since Math.random() returns a number from 0 up to but not including 1, if you cast it to int, it will round down to 0. Then when you multiply 10 to 0 you get 0.

like image 123
Hovercraft Full Of Eels Avatar answered Feb 15 '23 02:02

Hovercraft Full Of Eels


Math.random() returns a number from 0 to 1. You want to cast the result of (Math.random()*10) to int, not the number you get from Math.random itself. Numbers get rounded down. Therefore, for example, 0.3, which you can get from Math.random, gets rounded to 0. Again, you want to round the result of 0.3 times 10, which is 3. The parenthesis is important.

like image 32
Jobs Avatar answered Feb 15 '23 03:02

Jobs