Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abstract away the integer type in a mathematical software

I'm designing a mathematical software with algorithms that work for generic integer types such as machine ints, or GMP integers. For performance one usually wants to work with machine ints, but if there is an overflow, then one may want to try to switch to GMP; ideally at runtime. So far the entire program is written as a template over the integer type. As the library grows, the pain grows:

  • Compile time and memory consumption are getting out of hand.
  • Error messages at compile time are less useful.
  • Debugging is more painful.
  • The entire code is in header files.

I can think of the following solution. Refactor the code to depend on a fixed type that is typedef'ed via a compile time macro. Then make several copies of the library, one for each integer type and link them together in the executable. The drawback seems to be that I need an interface of the library to itself.

The short question would be: What are design patterns for situations in which almost the entire programm depends on a type?

like image 365
Thomas Avatar asked Jan 31 '13 16:01

Thomas


2 Answers

The GNU Multiple Precision Arithmetic Library has been

carefully designed to be as fast as possible, both for small operands and for huge operands.

In other words, if you use GMP library then that will handle these difficulties for you, and save you a lot of effort!

like image 162
danodonovan Avatar answered Nov 02 '22 21:11

danodonovan


In my own mathematical software, I use GMP by default but I want to provide a fallback if it is not available. I also didn't enjoy the huge gmpxx header file which slows down the compilation on my slow machine.

So I essentially wrote a wrapper class over an undefined integer (with pimpl using std::aligned_storage). The back end can be chosen during compilation time.

This gets rid of the templates and gives enough flexibility for me.

like image 39
ipc Avatar answered Nov 02 '22 20:11

ipc