The <tgmath.h> header, standardized in C 1999, provides typical calls for routines in <math.h> and <complex.h>. After you enable <tgmath.h>, the source text "sin (x)" will call sinl if x is a long double, sin if x is a double, and sinf if x is a float.
You will still need to conditionally adjust your constants so that you use "3.1" or "3.1f" depending on the situation. There are many syntactic methods for this, depending on your needs and what seems more aesthetic to you. For constants that are precisely represented in exactly float, you can simply use the float form. For example, "y = .5f * x" will automatically convert .5f to .5 if x is double. However, "sin (.5f)" will produce sinf (.5f), which is less accurate than sin (.5f).
Perhaps you can reduce convention to one clear definition:
#if defined USE_FLOAT typedef float Float; #else typedef double Float; #endif
Then you can use constants this way:
const Float pi = 3.14159265358979323846233; Float y = sin(pi*x); Float z = (Float) 2.71828182844 * x;
This may not be entirely satisfactory because there are rare cases when a number converted to double and then to float is less accurate than a number converted directly to float. That way, you might be better off with the macro described above, where βC (numeral)β appends the suffix to the number if necessary.
Eric Postpischil
source share