1

I am using the pow() function and I am trying to compare the return to a cpp_dec_float but I am getting an error

Code:

pow(sqrt(172.601), 2) != n);

Error:

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))
                          ^
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
İbrahim
  • 991
  • 1
  • 10
  • 32

1 Answers1

2

There are a number of pitfalls here. See the added links at the bottom.


Something tells me you've been using the backend type, not a frontend adaptor (like number<> or rational_adaptor<>).

The thing works without change:

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;
}

Prints

true

HOWEVER

You are mixing double and cpp_dec_float. This means that you do not gain much - if anything in the scenario - from the enhanced accuracy or decimal representation of Boost Multiprecision.

Instead consider going the whole way:

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;
}

Prints:

172.601
172.601
true

Note the CRUCIAL initialization from text, not a double literal!


Background info:

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633