在C / C如何(可移植)获得DBL_EPSILON ++ [英] How to (portably) get DBL_EPSILON in C/C++

查看:204
本文介绍了在C / C如何(可移植)获得DBL_EPSILON ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用GCC 3.4在Linux(AS 3),并试图找出让 DBL_EPSILON ,或者至少是一个体面的近似。我怎样才能得到它编程?

I am using GCC 3.4 on Linux (AS 3) and trying to figure out to get DBL_EPSILON, or at least a decent approximation. How can I get it programmatically?

推荐答案

它应该是float.h中。这就是便携,它的C和C ++标准的一部分(虽然C ++ pcated德$ P $ - 使用< cfloat> 或履行的回答为保证向前兼容) 。

It should be in "float.h". That is portable, it's part of the C and C++ standards (albeit deprecated in C++ - use <cfloat> or sbi's answer for "guaranteed" forward compatibility).

如果你没有的话,那么因为你的双打IEEE 64位,你可以偷别人的float.h中的价值。这里是第一个,我发现:

If you don't have it, then since your doubles are IEEE 64-bit, you can just steal the value from someone else's float.h. Here's the first one I found:

<一个href=\"http://opensource.apple.com/source/gcc/gcc-937.2/float.h\">http://opensource.apple.com/source/gcc/gcc-937.2/float.h

的#define DBL_EPSILON 2.2204460492503131e-16

值看上去只有我的权利,但如果你要确保你的编译器,你可以检查(1.0 + DBL_EPSILON)= 1.0安培;!&安培; (1.0 + DBL_EPSILON / 2)== 1.0

The value looks about right to me, but if you want to be sure on your compiler, you could check that (1.0 + DBL_EPSILON) != 1.0 && (1.0 + DBL_EPSILON/2) == 1.0

编辑:我不太清楚你所说的编程的意思。这是一个恒定的标准,你不应该来计算的话,这是一个头文件给你执行的属性。不过,我想你可以做这样的事情。同样,假设IEEE重新presentation或类似的东西,使DBL_EPSILON注定是不管的0.5重$ P $功率在1.0重presentation的precision的最后一位psents 1

I'm not quite sure what you mean by "programmatically". It's a standard constant, you aren't supposed to calculate it, it's a property of the implementation given to you in a header file. But I guess you could do something like this. Again, assuming IEEE representation or something like it, so that DBL_EPSILON is bound to be whatever power of 0.5 represents a 1 in the last bit of precision of the representation of 1.0:

double getDblEpsilon(void) {
    double d = 1;
    while (1.0 + d/2 != 1.0) {
        d = d/2;
    }
    return d;
}

要注意的是依赖于编译器设置,中间结果可能有更高的precision比双击,在这种情况下,你会得到的<$ C $一个较小的结果C> D 比 DBL_EPSILON 。检查你的编译器手册,或找到一种方法来强制 1.0 + D / 2 存储和重新加载到一个实际的双击对象,你把它比作 1.0 。粗略地讲,在PC上这取决于你的编译器是否使用的x86 FPU指令(高precision),或较新的64位浮点OPS(双precision)。

Beware that depending on compiler settings, intermediate results might have higher precision than double, in which case you'd get a smaller result for d than DBL_EPSILON. Check your compiler manual, or find a way to force the value of 1.0 + d/2 to be stored and reloaded to an actual double object before you compare it to 1.0. Very roughly speaking, on PCs it depends on whether your compiler uses the x86 FPU instructions (higher precision), or newer x64 floating point ops (double precision).

这篇关于在C / C如何(可移植)获得DBL_EPSILON ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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