I'm Trying to fill an array with a sine to create a sine table to be used instead of the sin function to decrease the amount of the calculation. Something is wrong with this C++ code, the array is always filled with the value 0.
#define TWO_PI (3.14159 * 2)
int16_t sineTable[32768];
const int32_t n = 32768;
const int16_t amp = 2047;
for ( int i = 0; i < n; i++ ) {
sineTable[i] = (sin(TWO_PI * (i / n)))*amp ;
//__android_log_print(ANDROID_LOG_INFO, "sometag", "test = %d", sineTable[3567]);
};
You can define sineTable as a double and define a better constant variable:
#define GRAD_TO_RAD (3.14159 * 2)/360
double sineTable[32768];
const int32_t n = 32768;
const int16_t amp = 2047;
for ( int i = 0; i < n; i++ )
{
sineTable[i] = amp * sin(i * GRAD_TO_RAD);
};
Note that john's comments might help also for a different solution or made a hybrid between our solutions.
Using lastchance comment we can optimize the O(N) code AND THE MEMORY by using only pi/2 iterations.
My idea for this is using the derivative concept. Therefore we can approach this by using de differential. Basically, we can know when we are going off pi/2, knowing sign[ΔѰ] != 1
, where ΔѰ will be differential between the last and new sin.
while (sin(i*GRAD_TO_RAD)>sin((i-1)*GRAD_TO_RAD))
{
sineTable[i] = amp * sin(i * GRAD_TO_RAD);
i++;
}
Note three imporant things here:
sineTable is a dynamic array.
This code it's just an example. Therefore, I think it will be way better codes to optimize what i just do. But I think it gets the idea.
Be aware of accesing the value in this array. Hint: define four type entries depending in what quadrant the angle is.
sineTable[x]
-sineTable[x]
-sineTable[s]
sineTable[s]
Where "s" it's a representation of the symetric angle: 2 * sin_table_lenght - x
.