Comparison of arbitrary arithmetic types: does anyone know the implementation?

When writing several mathematical applications, I was faced with the need to implement a universal utility that can perform a comparison between any two basic arithmetic types. When I started coding, it became clear that this operation is not as simple as it seems, because I need the correct handling of corner cases, especially when types have different accuracy, i.e. The rounding strategy when converting between types becomes important. Consider:

float a1 = 4.8f; int a2 = 4; assert(a2 != (int) a1); //fails erroneously since we truncated a1 float b1 = 40000000.0f; //can represent only 40000000 and 40000004 accurately long b2 = 40000002; assert(b1 != (float) b2); //fails erroneously since we now truncated b2 

The above can be implemented using properties of type C ++ 0x to automatically select the appropriate algorithm in accordance with the template arguments provided by the comparison function. However, itโ€™s quite difficult, and there are quite a few places where errors can creep, so I donโ€™t think of inventing everything that suits me. Does anyone know a library that correctly implements the above?

+6
source share
1 answer

You might want to explore the GNU MP Bignum library at http://gmplib.org/ . On your page:

GMP is a free library for arbitrary precision arithmetic, working on signed integers, rational numbers, and floating point numbers. There is no practical limit to accuracy other than those implied by the available memory in the GMP machine that works. GMP has a rich feature set, and functions have a regular interface.

GMP is carefully designed to be as fast as possible, both for small operands and for huge operands. Speed โ€‹โ€‹is achieved by using full words as the main arithmetic type, using fast algorithms, with highly optimized assembler code for the most common internal loops for many processors, as well as focusing on speed.

+1
source

Source: https://habr.com/ru/post/892944/


All Articles