gpt4 book ai didi

floating-point - 浮点相加与浮点乘以整数的精度

转载 作者:行者123 更新时间:2023-12-02 04:12:57 25 4
gpt4 key购买 nike

在我的计算机科学类(class)中,我们正在研究 float 以及它们在内存中的表示方式。我已经了解它们在内存中的表示方式(尾数/尾数、指数及其偏差以及符号位),并且我了解 float 如何彼此相加和相减(非规范化和所有这些有趣的东西)。然而,在查看一些学习问题时,我发现了一些我无法解释的事情。

当一个无法精确表示的 float 与自身相加多次时,答案会低于我们在数学上的预期,但当同一个 float 乘以一个整数时,答案会精确地得出正确的数字。

这是我们学习问题中的一个示例(该示例是用 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 之和,我们会得到略有不同的结果:

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;

for(float p=min; p <= max; p += width){
System.out.printf("%f%n", p);
}

我们得知,此测试中 p 的最终值为 ~9.999999,两者之间的差异为 -9.536743E-7 p 的最后一个值和 max 的值。从逻辑的角度来看(了解 float 如何工作),这个值是有意义的。

但我不明白的是,为什么我们在第一个示例中得到的结果恰好是 10.0。从数学上讲,我们得到 10.0 是有道理的,但知道 float 如何存储在内存中,这对我来说没有意义。谁能解释一下为什么我们通过将不精确的 float 与整数相乘来得到精确的值?

编辑:澄清一下,在最初的研究问题中,一些值被传递给函数,而其他值则在函数外部声明。我的示例代码是研究问题示例的缩短和简化版本。由于某些值被传递到函数中而不是显式定义为常量,因此我相信可以排除编译时的简化/优化。

最佳答案

首先,一些挑剔:

When a float that cannot be precisely represented

不存在“无法精确表示的 float ”。全部float s可以精确地表示为float s。

is added to itself several times, the answer is lower than we would mathematically expect,

当您多次将一个数字与自身相加时,您实际上可以得到比您预期更高的值。我将使用 C99 hexfloat notation 。考虑f = 0x1.000006p+0f 。然后f+f = 0x1.000006p+1f , f+f+f = 0x1.800008p+1f , f+f+f+f = 0x1.000006p+2f , f+f+f+f+f = 0x1.400008p+2f , f+f+f+f+f+f = 0x1.80000ap+2f ,和f+f+f+f+f+f+f = 0x1.c0000cp+2f 。然而,7.0*f = 0x1.c0000a8p+2 ,四舍五入为 0x1.c0000ap+2f ,小于f+f+f+f+f+f+f .

but when that same float is multiplied by an integer, the answer, comes out precisely to the correct number.

7 * 0x1.000006p+0f不能表示为 IEEE float 。因此它会被舍入。使用舍入到最近的舍入到偶数的默认舍入模式,当您执行这样的单个算术运算时,您将获得最接近精确结果的 float 。

The thing that I do not understand, though, is why we get exactly 10.0 for the first example. Mathematically, it makes sense that we would get 10.0, but knowing how floats are stored in memory, it does not make sense to me. Could anyone explain why we get a precise and exact value by multiplying an imprecise float with an int?

为了回答你的问题,你会得到不同的结果,因为你做了不同的操作。您在这里得到“正确”答案有点侥幸。

让我们交换一下数字。如果我计算0x1.800002p+0f / 3 ,我得到0x1.00000155555...p-1 ,四舍五入为 0x1.000002p-1f 。当我将其增加三倍时,我得到 0x1.800003p+0f ,四舍五入(因为我们打破平局)为 0x1.800004p+0f 。这与计算 f+f+f 得到的结果相同在float算术其中f = 0x1.000002p-1f .

关于floating-point - 浮点相加与浮点乘以整数的精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35513136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com