我有以下代码:
public static void Main(string[] args)
{
Console.WriteLine($"{Math.Round(0.5)} = round(0.5)");
Console.WriteLine($"{ToBinaryString(0.5)} = binary 0.5");
Console.WriteLine();
Console.WriteLine($"{Math.Log(1, 2)} = log2(1)");
Console.WriteLine($"{ToBinaryString(Math.Log(1, 2))} = binary log2(1)");
Console.WriteLine();
Console.WriteLine($"{Math.Round(Math.Log(1, 2) + 0.5)} = round(log2(1) + 0.5)");
Console.WriteLine($"{ToBinaryString(Math.Log(1, 2) + 0.5)} = binary log2(1) + 0.5");
Console.WriteLine();
Console.WriteLine($"{Math.Round(0.0 + 0.5)} = round(0.0 + 0.5");
Console.WriteLine($"{ToBinaryString(0.0 + 0.5)} = binary 0.0 + 0.5");
Console.WriteLine();
Console.WriteLine($"{Math.Log(1, 2) + 0.5 == 0.5} = Math.Log(1, 2) + 0.5 == 0.5");
Console.WriteLine($"{Math.Log(1, 2) == 0.0} = Math.Log(1, 2) == 0.0");
}
static string ToBinaryString(double value)
{
const int bitCount = sizeof(double) * 8;
long intValue = System.BitConverter.ToInt64(BitConverter.GetBytes(value), 0);
return Convert.ToString(intValue, 2).PadLeft(bitCount, '0');
}
输出为:
1 = round(0.5)
0011111111100000000000000000000000000000000000000000000000000000 = binary 0.5
0 = log2(1)
0000000000000000000000000000000000000000000000000000000000000000 = binary log2(1)
0 = round(log2(1) + 0.5) // ???? Why ????
0011111111100000000000000000000000000000000000000000000000000000 = binary log2(1) + 0.5
1 = round(0.0 + 0.5
0011111111100000000000000000000000000000000000000000000000000000 = binary 0.0 + 0.5
True = Math.Log(1, 2) + 0.5 == 0.5
True = Math.Log(1, 2) == 0.0
根据输出,我可以说,
Math.Log(1, 2)
恰好是 0
,而 Math.Log(1, 2) + 0.5
恰好是 0.5
。我认为是的,因为它们在内存中的表示是相等的。所以 double
类型的精度在这种情况下没有任何影响。如果我错了,请修复我。
但是
Math.Round(Math.Log(1, 2) + 0.5)
不等于Math.Round(0.5)
或Math.Round(0.0 + 0.5)
。怎么解释呢?