See what's going on with flipcode!




This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  Overlapping sin and cos Tables
  Submitted by



In case some people out there aren't doing this, here's a tip to keep your sin & cos lookup tables smaller saving on memory and thus possible cache misses. Not to mention initialisation being a fraction faster. How? Overlap them. As you probably know sin and cos differ only by a phase shift of 90degrees, so 3/4 of the cos table can be overlapped with the sin table. Here is a simple way to do this, which will never run slower than having the two tables seperate.

Additionally using a Fixed number format (like 16:16) to represent an angle rather than degrees, radians or gradians makes for a little more speed. (Unless you absolutely have to convert from degrees in realtime) i.e. 0-2047 (in fixed 16:16 format) = 0-360degrees.

#define WaveTableSize 2048
//These etc may be useful
#define FullCircle (WaveTableSize<<16)
#define NinetyDegrees (WaveTableSize<<14)
#define FortyFiveDegrees (WaveTableSize<<13)

float sn[(WaveTableSize+(WaveTableSize2))], *cs = &sn[WaveTableSize2];

void initTables() { for (int i=0; i<WaveTableTotalSize; ++i) sn[i]=sin(i * ((pi*2)/WaveTableSize)); }

inline int angleToIndex(int x) { return (x16) & (WaveTableSize-1); }

void blah(int angle) { int angle2 = angleToIndex(angle); float cosAngle = cs[angle2], sinAngle = sn[angle2]; ... }

Before you point it out, of course you can always make the tables smaller by storing only 90degrees of the sin curve and reflecting it various ways. That may be good for low memory circumstances.


The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.