[sdiy] OT - Linear interpolation in C

ASSI Stromeko at nexgo.de
Sun Jan 30 18:52:41 CET 2011


On Sunday 30 January 2011, Tom Wiltshire wrote:
> So how do I get C to treat a signed int as if it runs from -1 to 1 rather
> than -32768 to 32767? Or is there a better way?

Simple: you don't.  The data type required for this to work is not available 
in C, so you'd either need to deal with intrinsics or inline assembler or 
some horrible #pragma construction.  If you were using C++ and the compiler 
was recognizing some special classes for those datatypes you could hide it 
behind reasonably portable code.

However, I don't really understand what you're asking: the 8 bits you pull 
from the phase accumulator really are unsigned integers (or can be treated 
as such without any loss).  They tell you how many 1/256 steps you are 
between your two table lookups.  The interpolated value is then

/* arranged to have only one multiply and two adds */
interp = this + index * ((next - this) >> 8);

The obvious problem with this code is that it loses precision unless the 
compiler figures out all by itself or by gentle nudging that it can move the 
shift past the multiplication if it temporarily uses an accumulator (32bit 
most likely in this case, although 24bit would be enough).  So perhaps 
something contrived like

interp = (short)((long)this + (index * ((long)next - (long)this))) >> 8)

does the trick, but really I'd personally prefer to just go for inline 
assembly at that junction.  There are ways to improve the code above by 
looking at the magnitude of index and adjusting the shift accordingly 
(basically unrolling the adder tree that hides behind the multiply), but I 
think this is ill-advised for the dsPIC (unless the multiply takes much 
longer than an add).  This falls in the category of heroic optimization: the 
resulting code might be much portable, but the associated performance 
benefit is not.


Achim.
-- 
+<[Q+ Matrix-12 WAVE#46+305 Neuron microQkb Andromeda XTk Blofeld]>+

Factory and User Sound Singles for Waldorf Blofeld:
http://Synth.Stromeko.net/Downloads.html#WaldorfSounds



More information about the Synth-diy mailing list