Boost Using pow function with cpp_dec_float
我正在使用
码:
1 | pow(sqrt(172.601), 2) != n); |
错误:
1 2 3 | UserPath\\main.cpp:21: error: no match for 'operator!=' (operand types are '__gnu_cxx::__promote_2<double, int, double, double>::__type {aka double}' and 'boost::multiprecision::cpp_int {aka boost::multiprecision::number<boost::multiprecision::backends::cpp_int_backend<> >}') pow(sqrt(172.601), 2) != n)) ^ |
这里有很多陷阱。 请参阅底部添加的链接。
某些信息告诉我您一直在使用后端类型,而不是前端适配器(例如
事情没有改变就可以工作:
Live on Coliru
1 2 3 4 5 6 7 8 9 | #include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> int main() { boost::multiprecision::cpp_dec_float_50 n = 3; bool ok = pow(sqrt(172.601), 2) != n; std::cout << std::boolalpha << ok; } |
版画
1 | true |
然而
您正在混合
相反,请考虑全部进行:
Live on Coliru
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> int main() { typedef boost::multiprecision::cpp_dec_float_50 Decimal; Decimal n("172.601"); Decimal other = pow(sqrt(Decimal("172.601")), 2); std::cout << std::setprecision(50) << n <<"\ "; std::cout << std::setprecision(50) << other <<"\ "; bool equal = (abs(other - n) < std::numeric_limits<Decimal>::epsilon()); std::cout << std::boolalpha << equal; } |
印刷品:
1 2 3 | 172.601 172.601 true |
注意文本的CRUCIAL初始化,而不是
背景信息:
- 进行浮动和双重比较的最有效方法是什么?
- 使用boost lib的高精度浮点数(高于16位)