双>字符串>双重转换
为了通过网络传输数据,我将 double 转换为 string ,发送它并在接收端将其转换回 double 。 到目前为止,一切都很好。 但我偶然发现了一些我无法解释的奇怪行为
整个示例代码可以在此处找到。 我做什么: 通过 ostringstream
将 double 写入字符串,然后使用 istringstream
将其读入 值发生变化 但是如果我使用函数“strtod(...)”它就可以工作。 (具有相同的outstring
)
示例(整个代码可以在此处找到):
double d0 = 0.0070000000000000001;
out << d0;
std::istringstream in (out.str());
in.precision(Prec);
double d0X_ = strtod(test1.c_str(),NULL);
in >> d0_;
assert(d0 == d0X_); // this is ok
assert(d0 == d0_); //this fails
我想知道为什么会发生这种情况。
问题是:“为什么是‘istream>>’导致另一个结果为“strtod”” 请不要回答为什么 IEEE 754 不准确的问题。
To transport data over the network I convert a double to string , send it and on the receiver side convert it back to double.
so far so good.
But I stumbled over some weird behaviour which I'm not able to explain
The whole example code can be found here.
what i do:
Write a double to string via ostringstream
, afterwards read it in with istringstream
the value changes
But if i use the function "strtod(...) " it works. (with the same outstring
)
Example (the whole code can be found here):
double d0 = 0.0070000000000000001;
out << d0;
std::istringstream in (out.str());
in.precision(Prec);
double d0X_ = strtod(test1.c_str(),NULL);
in >> d0_;
assert(d0 == d0X_); // this is ok
assert(d0 == d0_); //this fails
I wonder why this happens.
The question is: "Why is 'istream >>' leading to another resulst as 'strtod'"
Please don't answer the question why IEEE 754 is no exact.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么它们可能不同:
http://www.parashift.com/c++-faq-lite /newbie.html#faq-29.16
http://www.parashift .com/c++-faq-lite/newbie.html#faq-29.17
如何比较浮点数:
http://c-faq.com/fp/strangefp.html
http://www.parashift.com/c++-faq-lite /newbie.html#faq-29.17
这是错误的方法:
如果您真正想要的是确保它们彼此“非常接近”(例如,如果变量 a 包含值 1.0 / 10.0 并且您想查看是否 (10*a = = 1)),您可能想做一些比上面更奇特的事情:
有很多方法可以定义 isEqual() 函数,包括:
注意:上面的解决方案并不完全对称,这意味着它可以isEqual(x,y) != isEqual(y,x)。从实际角度来看,当 x 和 y 的大小明显大于 epsilon 时,通常不会发生这种情况,但您的情况可能会有所不同。
Why are they might be different:
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.16
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.17
How to compare floating point:
http://c-faq.com/fp/strangefp.html
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.17
Here's the wrong way to do it:
If what you really want is to make sure they're "very close" to each other (e.g., if variable a contains the value 1.0 / 10.0 and you want to see if (10*a == 1)), you'll probably want to do something fancier than the above:
There are many ways to define the isEqual() function, including:
Note: the above solution is not completely symmetric, meaning it is possible for isEqual(x,y) != isEqual(y,x). From a practical standpoint, does not usually occur when the magnitudes of x and y are significantly larger than epsilon, but your mileage may vary.