gpt4 book ai didi

关于 C 语言中 DBL_EPSILON 和 Machine-Epsilon 的困惑

转载 作者:太空狗 更新时间:2023-10-29 15:21:57 30 4
gpt4 key购买 nike

Machine-Epsilon 似乎有两个定义:

  1. 将实数四舍五入到下一个 float 时的最大相对误差。
  2. 满足 1.0 + machine_eps != 1.0 的最小正数

首先,我看不出这两者之间有何关联。第二个 DBL_EPSILON 在我的理解中不符合定义 2:

以下程序打印:

DBL_EPSILON:            2.220446049250313080847e-16
DBL_EPSILON / 2: 1.110223024625156540424e-16
1.0 + DBL_EPSILON: 1.000000000000000222045e+00
1.0 + DBL_EPSILON / 2: 1.000000000000000000000e+00

m_eps 2.220446049250313080847e-16
m_eps -1u 2.220446049250312834328e-16

1.0 + m_eps -1u 1.000000000000000222045e+00

(m_eps -1u < DBL_EPSILON): True
(m_eps -1u == DBL_EPSILON/2): False

m_eps -1u 应该是一个更小但非常接近 DBL_EPSILON 的数字。和定义 2) 1.0 + m_eps -1u 不应计算为 1.0?为什么有必要为此将 DBL_EPSILON 设为 2?

#include <stdout.h>
#include <stdint.h>
#inlcude <float.h>

union Double_t {
double f;
int64_t i;
};

int main(int argc, char *argv[])
{
union Double_t m_eps;

printf("DBL_EPSILON: \t\t%.*e\n", DECIMAL_DIG, DBL_EPSILON);
printf("DBL_EPSILON / 2: \t%.*e\n", DECIMAL_DIG, DBL_EPSILON / 2);

printf("1.0 + DBL_EPSILON: \t%.*e\n", DECIMAL_DIG, 1.0 + DBL_EPSILON);
printf("1.0 + DBL_EPSILON / 2: \t%.*e\n", DECIMAL_DIG, 1.0 + DBL_EPSILON / 2);

m_eps.f = DBL_EPSILON;
printf("\nm_eps \t\t\t%.*e\n", DECIMAL_DIG, m_eps.f);

m_eps.i -= 1;
printf("m_eps -1u\t\t%.*e\n", DECIMAL_DIG, m_eps.f);
printf("\n1.0 + (m_eps -1u)\t\t%.*e\n", DECIMAL_DIG, 1.0 + m_eps.f);

printf("\n(m_eps -1u < DBL_EPSILON): %s\n",
(m_eps.f < DBL_EPSILON) ? "True": "False"
);

printf("(m_eps -1u == DBL_EPSILON/2): %s\n",
(DBL_EPSILON/2 == m_eps.f) ? "True": "False"
);
return 0;
}

最佳答案

DBL_EPSILON 的错误定义,您引用为“满足 1.0 + machine_eps != 1 的最小正数”的定义正在四处流传。您甚至可以在标准库和 StackOverflow 上的其他很好的答案中找到它。当在标准库中找到时,它在一个明显不对应于注释但对应于正确定义的值附近的注释中:

DBL_EPSILON: This is the difference between 1 and the smallest floating point number of type double that is greater than 1. (correct definition taken from the GNU C library)

C99 标准短语是这样的:

the difference between 1 and the least value greater than 1 that is representable in the given floating point type, b^(1−p)

这可能是您困惑的原因。忘记错误的定义。我写了一篇关于这个的咆哮here (这很像你的问题)。


您问题中的另一个定义“将实数舍入为下一个 float 时的最大相对误差”在舍入结果为正常 float 时是正确的。将实数四舍五入为有限 float 会产生与实数相差 1/2 ULP 以内的 float 。对于一个普通的 float ,这个 1/2 ULP 绝对误差转化为一个相对误差,它可以在 DBL_EPSILON/2 和 DBL_EPSILON/4 之间,具体取决于 float 在其 binade 中的位置。 .

关于关于 C 语言中 DBL_EPSILON 和 Machine-Epsilon 的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24584140/

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