在我的计算机科学课程中,我们正在研究浮点数及其在内存中的表示方式。我已经了解了它们在内存中的表示方式(尾数/有效数,指数及其偏倚以及符号位),并且我了解了浮点数是如何相互加减的(非正规化和所有这些有趣的东西)。但是,在研究一些学习问题时,我注意到一些我无法解释的问题。
当将无法精确表示的浮点数加到自身上时,答案要比我们在数学上期望的要低,但是当同一浮点数乘以整数后,答案就精确地得出了正确的数字。
这是来自我们研究问题的一个示例(该示例是用Java编写的,为了简单起见,我对其进行了编辑):
float max = 10.0f; /* Defined outside the function in the original code */
float min = 1.0f; /* Defined outside the function in the original code */
int count = 10; /* Passed to the function in the original code */
float width = (max - min) / count;
float p = min + (width * count);
在此示例中,我们被告知结果精确地为10.0。但是,如果我们将此问题视为浮点数的总和,则会得到略有不同的结果:
float max = 10.0f; /* Defined outside the function in the original code */
float min = 1.0f; /* Defined outside the function in the original code */