c++ - 将 pow 函数与 cpp_dec_float 结合使用

标签 c++ boost

我正在使用 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<> )。

事情没有改变就可以工作:

Live On Coliru

#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

然而

你在混doublecpp_dec_float .这意味着您不会从 boost 的精度或 Boost Multiprecision 的小数表示法中获得太多(如果在场景中有任何收获的话)。

而不是考虑一路走下去:

Live On Coliru

#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/

相关文章:

c++ - 如何等待子进程真正启动

c++ - C++中继承函数的链表中某一点插入的问题

c++ - 构建没有文件名修饰的 Boost?

c++ - 什么是仅 header 库

c++ - 传递带参数的 lambda

c++ - 将 std::vector<T> 转换为 char *

c++ - 如何打印作为参数传递的函数的名称?

c++ - MFC - UpdateData(False) + 线程 + 调试断言失败

c++ - 使用 boost::shared_ptr 进行多态转换

c++ - 来自一组源节点的 BGL dfs