3

在 C++ 中,由于 float 和 double 的精度有限,我使用以下代码计算出误差的数量级:

 float n=1;
 float dec  = 1;

 while(n!=(n-dec)) {
    dec = dec/10;
 }
 cout << dec << endl;

(在双重情况下,我所做的只是在第 1 行和第 2 行用 double 交换浮点数)

现在,当我在 Unix 系统上使用 g++ 编译和运行它时,结果是

Float  10^-8
Double 10^-17

但是,当我在 Windows 7 上使用 MinGW 编译和运行它时,结果是

Float  10^-20
Double 10^-20

这是什么原因?

4

3 回答 3

2

我想我会让我的评论成为答案并对其进行扩展。这是我的假设,我可能错了。

Windows 上的 MinGW 可能试图通过将表达式的中间体提升到 x86 的完整 80 位精度来保持精度。

因此,表达式的两边n != (n-dec)都被计算为 64 位精度(80 位 FP 具有 64 位尾数)。

2^-64 ~ 10^-20

所以这些数字是有道理的。

Visual Studio 也(默认情况下)将促进中间体。但只能达到双精度。

于 2011-10-09T08:09:07.947 回答
0

This simply shows that the different environments use different sizes for float and double.

According to the C++ specification, double has to be at least as large as float. If you want to find out just how large the types are on your system, use sizeof.

What your tests seem to indicate is that g++ uses separate sizes for float and double (32 and 64 bits respectively) while MinGW32 on your Windows system uses the same size for both. Both versions are standard conforming and neither behaviour can be relied upon in general.

于 2011-10-09T08:23:05.743 回答
0

为什么不检查两个操作系统中的 float 和 double 的大小?

于 2011-10-09T08:04:31.040 回答