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 :
int result = 0; result += Math.random() + 1;
Why?
Putting the compiled code in a nested loop, we can expect that the result will increase by 1 with each iteration, because Math.random () always returns double, whose value is less than 1, and when added to an integer, the fractional part will be lost due to loss of accuracy. Run the following code and you will see an unexpected result:
public class MathRandomCuriosity { public static void main(String[] args) { int result = 0; for (int i = 0; i < 10; i++) {
With 10 * 20 * 300 * 7000 = 42,000,000 iterations, the result should be 42,000,000. But this is not so! The result varies, for example, 42 000 007 against 42 000 006 against 42 000 010, etc.
Why?
By the way ... this is not a code that is used anywhere, it is the result of a quiz that I received in the newsletter. The reason for nested loops is that I can view the value of the result at intervals.
source share