关于c ++:使用ppp函数和cpp_dec_float进行增强

Boost Using pow function with cpp_dec_float

我正在使用pow()函数,并且试图将返回值与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))
                          ^

这里有很多陷阱。 请参阅底部添加的链接。

某些信息告诉我您一直在使用后端类型,而不是前端适配器(例如number<>rational_adaptor<>)。

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

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

然而

您正在混合doublecpp_dec_float。 这意味着您不会从Boost Multiprecision的增强的准确性或十进制表示中获得太多收益(如果在方案中有任何收益)。

相反,请考虑全部进行:

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初始化,而不是double文字!

背景信息:

  • 进行浮动和双重比较的最有效方法是什么?
  • 使用boost lib的高精度浮点数(高于16位)