我正在使用 pow()
函数,我正在尝试将返回值与 cpp_dec_float
进行比较,但出现错误
代码:
pow(sqrt(172.601), 2) != n);
错误:
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))
^
最佳答案
这里有很多陷阱。请参阅底部添加的链接。
有些东西告诉我你一直在使用后端类型,而不是前端适配器(如 number<>
或 rational_adaptor<>
)。
事情没有改变就可以工作:
#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;
}
打印
true
然而
你在混double
和 cpp_dec_float
.这意味着您不会从 boost 的精度或 Boost Multiprecision 的小数表示法中获得太多(如果在场景中有任何收获的话)。
而不是考虑一路走下去:
#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 << "\n";
std::cout << std::setprecision(50) << other << "\n";
bool equal = (abs(other - n) < std::numeric_limits<Decimal>::epsilon());
std::cout << std::boolalpha << equal;
}
打印:
172.601
172.601
true
请注意 text 的 CRUCIAL 初始化,而不是 double
字面意思!
背景信息:
关于c++ - 将 pow 函数与 cpp_dec_float 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35042422/