我正在使用用于十进制浮点类型的 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
我尝试用 precision() 来“截断”,但没有成功。 有没有办法在不使用 epsilon 比较的情况下比较两个数字?
最佳答案
如果剥离保护位,则会有效地削弱预期类型的保真度。
确实,一种万无一失的方法是使用(反)序列化。
所以我建议
// 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/