在 C++ 中编写一个全精度浮点数
在 C++ 中,我可以以文本格式写入和读回浮点型(或双精度型)而不丢失精度吗?
考虑以下因素:
float f = ...;
{
std::ofstream fout("file.txt");
// Set some flags on fout
fout << f;
}
float f_read;
{
std::ifstream fin("file.txt");
fin >> f;
}
if (f != f_read) {
std::cout << "precision lost" << std::endl;
}
我理解为什么有时会丢失精度。但是,如果我用足够的数字打印该值,我应该能够读回完全相同的值。
是否有一组给定的标志可以保证永远不会丢失精度? 这种行为可以跨平台移植吗?
In C++, can I write and read back a float (or double) in text format without losing precision?
Consider the following:
float f = ...;
{
std::ofstream fout("file.txt");
// Set some flags on fout
fout << f;
}
float f_read;
{
std::ifstream fin("file.txt");
fin >> f;
}
if (f != f_read) {
std::cout << "precision lost" << std::endl;
}
I understand why precision is lost sometimes. However, if I print the value with enough digits, I should be able to read back the exact same value.
Is there a given set of flags that is guaranteed to never lose precision?
Would this behaviour be portable across platforms?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您不需要支持缺乏 C99 支持 (MSVC) 的平台,那么最好的选择实际上是使用
%a
格式说明符和printf
,它总是生成使用有限位数的数字的精确(十六进制)表示。如果使用此方法,则在转换为字符串或返回字符串期间不会发生舍入,因此舍入模式对结果没有影响。If you don't need to support platforms that lack C99 support (MSVC), your best bet is actually to use the
%a
format-specifier withprintf
, which always generates an exact (hexadecimal) representation of the number while using a bounded number of digits. If you use this method, then no rounding occurs during the conversion to a string or back, so the rounding mode has no effect on the result.查看这篇文章:如何准确打印浮点数 以及那个:快速准确地打印浮点数。
stackoverflow 此处也提到了这一点,并且有一些指向实现的指针此处。
Have a look at this article: How to Print Floating-Point Numbers Accurately and also at that one: Printing Floating-Point Numbers Quickly and Accurately.
It is also mentioned on stackoverflow here, and there is some pointer to an implementation here.
如果你用十进制写它则不然 - 二进制位数和表示数字所需的十进制位数之间没有整数关系。如果您以二进制或十六进制打印数字,您将能够读回它而不会丢失任何精度。
一般来说,浮点数首先不可在平台之间移植,因此您的文本表示无法弥补这一差距。实际上,大多数机器都使用 IEEE 754 浮点数,因此它可能会工作得相当好。
Not if you write it in decimal - there's not an integer relationship between the number of binary digits and the number of decimal digits required to represent a number. If you print your number out in binary or hexadecimal, you'll be able to read it back without losing any precision.
In general, floating point numbers are not portable between platforms in the first place, so your text representation is not going to be able to bridge that gap. In practice, most machines use IEEE 754 floating point numbers, so it'll probably work reasonably well.
您不一定能以十进制形式打印“二的幂”浮点数的精确值。
考虑使用基数 3 来存储 1/3,现在尝试完美地以十进制打印 1/3。
有关解决方案,请参阅:如何打印浮点数的精确值?
You can't necessarily print the exact value of a "power of two" float in decimal.
Think of using base three to store 1/3, now try and print 1/3 in decimal perfectly.
For solutions see: How do you print the EXACT value of a floating point number?