gpt4 book ai didi

c++ - 带 IEEE 754 float 的有效数字

转载 作者:太空宇宙 更新时间:2023-11-04 13:33:05 26 4
gpt4 key购买 nike

维基 Double-precision floating-point format说:

This gives 15–17 significant decimal digits precision. If a decimal string with at most 15 significant digits is converted to IEEE 754 double precision representation and then converted back to a string with the same number of significant digits, then the final string should match the original. If an IEEE 754 double precision is converted to a decimal string with at least 17 significant digits and then converted back to double, then the final number must match the original.

任何人都可以给我一些例子来说明转换如何与原始匹配,以及在哪些情况下不匹配?

最佳答案

有 15 位有效数字,从字符串到 double 再返回...

std::istringstream iss("0.123456789012345");
double d;
iss >> d;
std::ostringstream oss;
oss << std::fixed << std::setprecision(15) << d;
std::cout << "should be 0.123456789012345 but might have changed: " << oss.str() << '\n';

注意:对于一些 15 位有效数字的初始输入字符串,上述代码可能输出不同的最终字符串。这是一个程序,它试图找到一个 15 位数字的字符串输入,其值不会通过与 double 的转换而保留,而是 all values pass for GCC on coliru.stackedcrooked.com 。这并不意味着它不会因不同范围内的某些其他值而失败。

#include <sstream>
#include <iostream>
#include <iomanip>

int main()
{
int results = 0;

for (unsigned long i = 0; i <= 999999999999999; ++i)
{
std::ostringstream oss;
oss << "0." << std::setfill('0') << std::setw(15) << i;
std::istringstream iss(oss.str());
double d;
iss >> d;
std::ostringstream oss2;
oss2 << std::fixed << std::setprecision(15) << d;
if (oss.str() != oss2.str())
{
std::cout << "from " << oss.str() << '\n' << " to " << oss2.str() << '\n';
if (++results > 50) exit(0);
}
}
}

有 17 位有效数字,从 double 到字符串再返回...

double d = 0.12345678901234567;
std::ostringstream oss;
oss << std::fixed << std::setprecision(17) << d;
std::istringstream iss(oss.str());
double d2;
iss >> d2;
std::cout << "d must equal d2: " << std::boolalpha << d == d2 << '\n';

这应该永远无法从文本表示中恢复相同的 double 值。

关于c++ - 带 IEEE 754 float 的有效数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30722487/

26 4 0
文章推荐: javascript - jQuery 无法访问追加元素
文章推荐: java - 从 Selenium 的隐藏下拉菜单中选择一个选项
文章推荐: jquery - 使
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com