Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ decimal arithmetic libraries

Tags:

c++

boost

I'm fairly new to adding additional libraries to Visual Studio (2013) as well as the idea that floats and doubles are usually not accurate enough when dealing with certain things like money. I originally thought that BOOST::Multiprecision cpp_dec_float would solve this problem but as I tested it I noticed some unusually things and realized that I could be wrong. for example,

cpp_dec_float_50 decimal = 0.45;
double dbl = 0.45; //for comparison

cout << fixed << setprecision(50) << "boost:    " << decimal << endl;
cout << "double:  " << dbl << endl;

would give results like this

boost:    0.45000000000000001110223024625156540423631668090820
double:   0.45000000000000001000000000000000000000000000000000

instead of what I expected (0.45000000000000000000000000000000000000000000000000).

is this not going to be much more accurate than just using floats or doubles? If not, I'm assuming the boost library I just linked to my VS2013 has an arbitrary integer type, would this be acceptable? the only thing I don't like about using integers for such a thing is that I'd probably have to convert interest rates into integers before multiplying it with currency which would likely result in a very, very large number which may or may not cause performance issues.

(assuming BOOST isn't what I need) what are your thoughts on Intel's Decimal Floating-Point Library? I couldn't get it to work (yet) so I'm wondering if it is worth the effort. Are there any other similar libraries worth checking out?

like image 413
Naka Avatar asked Jan 25 '15 06:01

Naka


1 Answers

So, you're assigning a number (that is already in floating point) to your decimal variable. So the error that you are concerned about has already been introduced.

Instead, let's assign it with a string containing the correct number:

#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
using namespace std;
using boost::multiprecision::cpp_dec_float_50;

int main() {
    cpp_dec_float_50 decimal("0.45");
    double dbl = 0.45; //for comparison

    cout << fixed << setprecision(50) << "boost:   " << decimal << endl;
    cout << "double:  " << dbl << endl;
}

Which outputs:

boost:   0.45000000000000000000000000000000000000000000000000
double:  0.45000000000000001110223024625156540423631668090820
like image 136
Bill Lynch Avatar answered Oct 16 '22 06:10

Bill Lynch