下無法編譯:的Math.random()與精度損失好奇心
int result = Math.random() + 1;
error: possible loss of precision
int result = Math.random() + 1;
^
required: int
found: double
但以下確實編譯:
int result = 0;
result += Math.random() + 1;
爲什麼?
將可編譯代碼放入嵌套循環中,每次迭代都會使結果增加1,因爲Math.random()始終返回值小於1的double值,並且在將小數部分添加到整數時由於精確度損失而丟失。運行下面的代碼,看到了意想不到的結果:
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);
}
}
隨着10 * 20 * 300 * 7000 = 42000000次的迭代的結果應該是42000000。但它不是!結果變化,即42,000,007與42,000,006與42,000,010等相關。
爲什麼?
順便說一句...這不是任何地方正在使用的代碼,它來自我在簡報中收到的測驗。嵌套循環的原因是我可以間隔地查看結果的值。
在一般情況下,這個問題已經被多次解答。 – Woot4Moo
編寫'for(int i = 0; i <42000000; i ++)的奇怪方法' –
嘗試將Math.random()調用先轉換爲整數。目前,代碼中的'1'字面意味着被隱式轉換爲double,這意味着某處會丟失精度。 –