由于float和double的精度有限,导致错误 [英] Error due to limited precision of float and double

查看:138
本文介绍了由于float和double的精度有限,导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  float n = 1; 
float dec = 1;

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

(在双重情况下,我所做的是在第1行和第2行交换float double) p>

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

  Float 10 ^ -8 
Double 10 ^ -17

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

 浮点数10 ^ -20 
双10 ^ -20

这是什么原因?

解决方案

我想我会让我的评论一个答案,并扩大它。 这是我的假设,我可能会错。



Windows上的MinGW可能通过将表达式的中间体因此,表达式 n!=(n-dec)的两边都可以使用x86的80位精度。



<被评估为64位精度(80位FP具有64位尾数)。

  2 ^ -64〜 10 ^ -20 

所以数字是有意义的。



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


In C++, I use the following code to work out the order of magnitude of the error due to the limited precision of float and double:

 float n=1;
 float dec  = 1;

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

(in the double case all I do is exchange float with double in line 1 and 2)

Now when I compile and run this using g++ on a Unix system, the results are

Float  10^-8
Double 10^-17

However, when I compile and run it using MinGW on Windows 7, the results are

Float  10^-20
Double 10^-20

What is the reason for this?

解决方案

I guess I'll make my comment an answer and expand on it. This is my hypothesis, I may be wrong.

MinGW on Windows is probably trying to preserve precision by promoting the intermediates of expressions to the full 80-bit precision of x86.

Therefore, both sides of the expression n != (n-dec) are evaluated to 64-bits of precision (80-bit FP has a 64-bit mantissa).

2^-64 ~ 10^-20

So the numbers make sense.

Visual Studio also (by default), will promote intermediates. But only up to double-precision.

这篇关于由于float和double的精度有限,导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆