为什么这个 stl 函数返回这个 double 值?

发布于 2024-12-14 09:03:26 字数 468 浏览 3 评论 0原文

以下断言在 RAD Studio 2010 中失败(顺便说一句,在 Visual Studio 2010 中会成功):

double              d1 = 0.0104;
double              d2 = 0.0;
std::istringstream  ss("0.0104");
ss >> d2;
assert(d1 == d2);

这让我有点惊讶。我追踪到提取操作符以查看发生了什么,一直追踪到 dinkumware/xlocnum,但无法进一步追踪。

谁能告诉我为什么 __Stodx(... "0.0104") 返回的值与初始化为 0.0104 的双精度值略有不同?

(我知道某些值无法用二进制精确表示。我想知道为什么结果双精度数包含不同的值,以便我可以理解它。)

谢谢!

The following assertion fails in RAD Studio 2010 (and incidentally would succeed in Visual Studio 2010):

double              d1 = 0.0104;
double              d2 = 0.0;
std::istringstream  ss("0.0104");
ss >> d2;
assert(d1 == d2);

This surprised me a little. I traced down into the extraction operator to see what was happening, got as far as dinkumware/xlocnum, and couldn't trace any further.

Can anyone tell me why __Stodx(... "0.0104") returns a value that's marginally different from a double initialized to 0.0104?

(I know that certain values can't be represented exactly in binary. What I want to know is why the resultant doubles contain different values so that I can understand it.)

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撩动你心 2024-12-21 09:03:26

这是这个问题的答案

[29.17] 为什么我的浮点比较不起作用?

因为浮点运算与实数不同
算术。

底线:切勿使用 == 来比较两个浮点数。

这里关于“为什么结果双精度数包含不同值”的答案

  1. d1 是编译器提供的精确常量表示形式
  2. d2 在转换期间计算(参见 strtod),因此在浮点计算过程中可能会出现一些舍入误差,如此处此处

Here the answer to this question.

[29.17] Why doesn't my floating-point comparison work?

Because floating point arithmetic is different from real number
arithmetic.

Bottom line: Never use == to compare two floating point numbers.

Here the answer on "why the resultant doubles contain different values"

  1. d1 is exact constant representation provided by compiler
  2. d2 is computed during conversion (see example of strtod), so it can be some rounding errors during floating-point calculation as described here and here
不喜欢何必死缠烂打 2024-12-21 09:03:26

亲爱的我:编译器和库使用不同的方法将字符串转换为双精度,如果无法访问编译器源代码,没有人能够告诉您这些方法有何不同。

对不起,

Dear Me: The compiler and library use different methods to convert strings to doubles, and without access to the compiler source, nobody is going to be able to tell you how those methods differ.

Sorry,
Me

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文