After struggling with C code for a while I've managed to make a function which calculates the arctangent value by means of a lookup table, which is much faster than recalculating the arctangent value each time it is needed. But is it actually faster than the arctan in the Arduino library?
//=================================================== //==== lookup table for arctan (testing 123..) ====== //=================================================== float scale_float = 10.0; // used to increase number of points in LUT_atan array const int scale_int = 10; const int w = 20 * scale_int; float LUT_atan_array[w]; // should be 20*scale, but am struggling with the syntax void make_atan_array() { for (int i = 0; i < (20 * scale_int+1); i++) { LUT_atan_array[i] = atan(int(i) / scale_float); } } float LUT_atan(float rads_in) { float num = rads_in * scale_float; int is_negative; if (num < 0) { is_negative = 1; num = num - 2*num; } else { is_negative = 0; } // pick a point in the array below num and above num int X0 = int(num); int X1 = X0 + 1; float Y0 = LUT_atan_array[X0]; float Y1 = LUT_atan_array[X1]; // linearly interpolate between points in array float slope = (Y1 - Y0); float result = Y0 + (num - X0) * slope; if (is_negative == 1) // if input was negative, make the array output negative { result = result - 2 * result; return result; } else { return result; } }Writing this in python was easy, doing it in C: not so easy. I found a way to run it against the actual arctangent function and print the values comparing them to serial. It is accurate to 3 decimal places. Timing how long it took to do 10,000 iterations (approximately 130milli seconds on an Arduino Mega 2560) showed that my function was about two or three miliseconds slower per 10,000 iterations than the atan function in the Arduino library, which is dissapointing. This means the Arduino math library is probably already using a similar lookup table method.
Oh well. Now I know more about C++ and lookup tables :)
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.