[En-Nut-Discussion] Fixed-point library

Stefan Hax stefan at escherlogic.com
Tue Sep 24 14:07:30 CEST 2013



Harald Kipp wrote:
> Hi all,
> 
> Almost no embedded application I wrote so far required floating point
> values. It is usually sufficient to scale ranges to integer values, e.g.
> 2075 representing 20.75.
> 
> But now I need trigonometric functions, which are not available for
> scaled integers, right? Actually it may be possible to write my own, but
> I'd prefer a more general solution.
> 
> I'd very much appreciate, when members of this list will share their
> experience, if there are any.
> 
If this helps, I do these calculations still as integers. Here are my 
examples of sine() and cosine(), 64-bit internal and returning 32-bit.

Stefan.

#define A100 100000LL           // A full scale
#define P4    78540LL           // pi / 4 x A  or  pi / 4 x full scale

#define BSIN (A100 * 6LL)       // A x 6 = 196608
#define BCOS (A100 * 2LL)       // A x 2 = 65536
#define CCOS (A100 * 12LL)      // A x 12 = 393216

//************************************************************************
// Integer sine function for angles <= +/-45 degrees
// error increases outside this range e.g. +/-90 deg error < 0.5%
// returns as a ratio of A (A100) e.g. 1.00 = 100000
//
// input: deg x 10
int32_t isin(int32_t deg)
{
long long xrad, sxr;

     xrad = ((long long)deg * P4) / 450; // Convert to radians
     sxr = (xrad * xrad) / A100;

     return ( (long)((xrad * (A100 - (sxr * (A100 - sxr / 20)) / BSIN)) 
/ A100) );
}


//************************************************************************
// Integer cosine function for angles <= +/-45 degrees
// error increases outside this range e.g. +/-90 deg error < 0.5%
// returns as a ratio of A (A100) e.g. 1.00 = 100000
//
// input: deg x 10
int32_t icos(int32_t deg)
{
long long xrad, sxr;

     if (deg == 0)  return ( (long)A100 );       // trivial sol'n

     xrad = ((long long)deg * P4) / 450;         // Convert to radians
     sxr = (xrad * xrad) / A100;

     return ( (long)(A100 - (sxr * (A100 - (sxr * (A100 - sxr / 30)) / 
CCOS)) / BCOS) );
}


More information about the En-Nut-Discussion mailing list