Using boost multiprecision with trigonometric function

837 Views Asked by At

Consider the following code which creates a multiprecision floating-point number 'a' by using boost.

How do I use boost library to invoke trigonometric functions? For example, I hope to calculate sin(a).

#include <iostream>
#include "boost/multiprecision/cpp_bin_float.hpp"

using namespace std;
using namespace boost::multiprecision;

typedef number<backends::cpp_bin_float<24, backends::digit_base_2, void, boost::int16_t, -126, 127>, et_off> float32;

int main (void) {
  float32 a("0.5");

  return 0;
}
2

There are 2 best solutions below

1
On BEST ANSWER

It looks like there is a limitation in the library. When the precision is dropped too low, the sin implementation no longer compiles.

Some intermediate calculations are being done in double precision. The assignment into the result type would be lossy and hence doesn't compile.

Your chosen type actually corresponds to cpp_bin_float_single. That doesn't compile.

As soon as you select cpp_bin_float_double (precision 53 binary digits) or higher, you'll be fine.


I suppose this limitation could be viewed as a bug in some respects. You might report it to the library devs, who will be able to judge whether the related code could use single-precision floats there without hurting the convergence of the sin approximation.

0
On
#include <boost/multiprecision/cpp_bin_float.hpp>
#include <iostream>
using namespace std;
using namespace boost::multiprecision;
int main() {
    cpp_bin_float_100 a = 1;
    cout << setprecision(50) << endl;
    cout << sin(a) << endl;
    return 0;
}

I've verified digits with Wolfram Mathematica and they are correct:

enter image description here