C preprocessor evaluates sin () constants

Is there a way to convince the C preprocessor to evaluate the constant transcendental function at compile time?

For example, replace (int)256*sin(PI/4)

with 181

. This will help me keep the magic numbers out of my code.

If it matters, I'm using MSPGCC 4.5.3 and I don't have sin()

or cos()

are available at runtime.


source to share

4 answers

As long as your arguments are within the range [-ฯ€ / 4, + ฯ€ / 4], you can use the same standard libm implementations to compute sin. It is corrected to the last place (maximum allowable error is 1), as in the IEEE standard:

static const double 
half =  5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */
S1  = -1.66666666666666324348e-01, /* 0xBFC55555, 0x55555549 */
S2  =  8.33333333332248946124e-03, /* 0x3F811111, 0x1110F8A6 */
S3  = -1.98412698298579493134e-04, /* 0xBF2A01A0, 0x19C161D5 */
S4  =  2.75573137070700676789e-06, /* 0x3EC71DE3, 0x57B1FE7D */
S5  = -2.50507602534068634195e-08, /* 0xBE5AE5E6, 0x8A2B9CEB */
S6  =  1.58969099521155010221e-10; /* 0x3DE5D93A, 0x5ACFD57C */

double __kernel_sin(double x, double y, int iy)
    double z,r,v;
    int ix;
    ix = __HI(x)&0x7fffffff;    /* high word of x */
    if(ix<0x3e400000)           /* |x| < 2**-27 */
       {if((int)x==0) return x;}        /* generate inexact */
    z   =  x*x;
    v   =  z*x;
    r   =  S2+z*(S3+z*(S4+z*(S5+z*S6)));
    if(iy==0) return x+v*(S1+z*r);
    else      return x-((z*(half*y-v*r)-y)-v*S1);


Source: http://www.netlib.org/fdlibm/k_sin.c

While not what I would call nice, you can definitely convert this whole function into a macro that will evaluate a floating point constant expression (compile time). (Ignore the hacker bit at the beginning, which has nothing to do with the value, and as far as I know, you should assume it iy

is 0.)



The C preprocessor cannot provide sin () or cos ().

For my applications, I use a perl script to create a separate .h file containing the necessary pre-calculations. There are probably sexier ways to do this, but it integrates very well into my workflow.



The preprocessor can only allow macros, which is no different from executing a function. The closest solution I can think of to reduce your magic numbers is to create a header with the most commonly used sin or coincidence meanings:

#define SIN_PI  (-1)
#define SIN_PI2 0
#define SIN_PI4 0.707106781186548


Then you can write:



And let the compiler optimization reduce it to one constant.



C ++ is much more ambitious about the initialization it will do. Is it possible to upgrade to g ++ version, did it include mspgcc?

Edit: After a bit of searching their websites and email archives AFAICT mspgcc doesn't support g ++ :-( This would be a very lightweight solution.



All Articles