The following does not compile:
int result = Math.random() + 1;
error: possible loss of precision
int result = Math.random() + 1;
^
required: int
found: double
but the following does compile:
int result = 0;
result += Math.random() + 1;
Why?
Putting the compilable code into a nested loop, one would expect result to increment by 1 with each iteration because Math.random() always returns a double whose value is less than 1 and when added to an integer the fractional part would be lost due to precision loss. Run the following code and see the unexpected result:
public class MathRandomCuriosity
{
public static void main(String[] args)
{
int result = 0;
for (int i = 0; i < 10; i++)
{
// System.out.println(result);
for (int j = 0; j < 20; j++)
{
// System.out.println(result);
for (int k = 0; k < 300; k++)
{
// System.out.println(result);
for (int m = 0; m < 7000; m++)
{
result += Math.random() + 1;
}
}
}
}
System.out.println(result);
}
}
With 10*20*300*7000 = 42,000,000 iterations the result should be 42,000,000. But it's not! The result varies i.e. 42,000,007 vs. 42,000,006 vs. 42,000,010 etc.
Why?
By the way...this is not code that is being used anywhere, it comes from a quiz I received in a newsletter. The reason for the nested loops is so that I can view the value of result at intervals.