I am developing a library of special-purpose math functions in C. I need to provide a capability for the library to handle both single-precision and double-precision. The important point here is that the “single” functions should use ONLY “single” arithmetic internally (resp. for the “double” functions).
As an illustration, take a look at LAPACK (Fortran), which provides two versions of each of its function (SINGLE and DOUBLE). Also the C math library (example, expf and exp).
To clarify, I want to support something similar to the following (contrived) example:
float MyFloatFunc(float x) {
return expf(-2.0f * x)*logf(2.75f*x);
}
double MyDoubleFunc(double x) {
return exp(-2.0 * x)*log(2.75*x);
}
I’ve thought about the following approaches:
-
Using macros for the function name. This still requires two separate source codebases:
#ifdef USE_FLOAT #define MYFUNC MyFloatFunc #else #define MYFUNC MyDoubleFunc #endif -
Using macros for the floating point types. This allows me to share the codebase across the two different versions:
#ifdef USE_FLOAT #define NUMBER float #else #define NUMBER double #endif -
Just developing two separate libraries, and forgetting about trying to save headaches.
Does anyone have a recommendation or additional suggestions?
For polynomial approximations, interpolations, and other inherently approximative math functions, you cannot share code between a double-precision and a single-precision implementation without either wasting time in the single-precision version or being more approximative than necessary in the double-precision one.
Nevertheless, if you go the route of the single codebase, the following should work for constants and standard library functions: