boost 多精度 cpp_dec_float 仅与所需精度进行比较

标签 boost floating-point compare decimal multiprecision

我正在使用用于十进制浮点类型的 boost::multi precision 库,并且希望将两个浮点与指定的精度进行比较。

但是,cpp_dec_float 似乎没有将数字与指定的精度进行比较,但还包括保护数字:

#include <iostream>

#include <boost/multiprecision/cpp_dec_float.hpp>
//#include <boost/math/special_functions.hpp>

typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<50> > flp_type;

int main(int argc, char* argv[])
{
    // 50 decimal digits
    flp_type sqrt2("1.4142135623730950488016887242096980785696718753769");
    // Contains calculated guard digits
    flp_type result(boost::multiprecision::sqrt(flp_type("2")));

    // The 50 digits of precision actually ompare equal
    std::cout << std::setprecision(50) << sqrt2 << std::endl;
    std::cout << std::setprecision(50) << result << std::endl;
    // I want this to compare to the specified precision of the type, not the guard digits
    std::cout << (result==sqrt2) << std::endl;

    return 0;
}

输出:

1.4142135623730950488016887242096980785696718753769
1.4142135623730950488016887242096980785696718753769
0

预期:

1.4142135623730950488016887242096980785696718753769
1.4142135623730950488016887242096980785696718753769
1

See on Coliru

我尝试用 precision() 来“截断”,但没有成功。 有没有办法在不使用 epsilon 比较的情况下比较两个数字?

最佳答案

如果剥离保护位,则会有效地削弱预期类型的​​保真度。

确实,一种万无一失的方法是使用(反)序列化。

所以我建议

Live On Coliru

// Either
std::cout << std::numeric_limits<flp_type>::epsilon() << "\n";
std::cout << (abs(result-sqrt2) < std::numeric_limits<flp_type>::epsilon()) << std::endl;

// Or
result = flp_type { result.str(49, std::ios::fixed) };
std::cout << (result==sqrt2) << std::endl;

请注意,epsilon 是 1e-49

打印

1.4142135623730950488016887242096980785696718753769
1.4142135623730950488016887242096980785696718753769
1e-49
1
1

显然,基于 epsilon() 的比较会显得更有效

关于 boost 多精度 cpp_dec_float 仅与所需精度进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27378800/

相关文章:

c++ - 抛出一个 std::length_error 实例,示例需要 boost

javascript - 比较 Javascript 中的十进制字符串

opengl - 为什么除法产生的结果与 float 乘以分数的结果截然不同

php - 比较来自 mysql 的 PHP 中的 2 个日期时间,以便在 android 中查看

string - 基于预先计算的散列比较字符串距离

c++ - 使用Boost::Asio套接字读取500ms

c++ - 迭代超出范围,并且 "one more"

c++ - 如何在boost::program_options::variable_map中存储数据?

algorithm - 为什么标准化数字的最高有效位总是 1?

java - 如何比较任何对象的两个实例并获取 "dirty"字段