CCS does not monitor this forum on a regular basis. Please do not post bug Reports on this forum. Send them to support@ccsinfo.com
Author Message
Ttelmah

Joined: 11 Mar 2010
Posts: 14622

Fast trigonometric approximations
Posted: Fri Jun 09, 2017 2:50 pm

Some time ago, I posted a much faster atan2 in the general forum.
Decided to post it here together with another fast set of code for sin and cosine:

The accuracy is better than half a degree, and it is _fast_. Takes about 70uSec on a 40Mhz PIC, while atan2 takes at least ten times longer. It is also smaller.... It only gives positive angles, from 0 to 360 as it's result. This works in degrees but is easy to convert to radians if required.

Now I have added this code for sin/cosine. This is in radians for +PI to -PI input range.
 Code: //A fast float approximation to sin over the range +/-PI #define PI2 (PI*PI) #define INV4  (4/PI) #define INV4SQ  (-4/(PI2)) #define P  0.225 float fast_sin(float x) {     float y;     y = (INV4 * x) + (INV4SQ * x * fabs(x));     return P * (y * fabs(y) - y) + y;    } float fast_cos(float x) {  //This is done by shifting the quadrants    x += PIDIV2;    if(x > PI)   // Original x > pi/2    {       x -= PI2;   // Wrap: cos(x) = cos(x - 2 pi)    }    return fast_sin(x); } void main(void) {   //Test the fast sin algorithm for angles from 0 to PI in steps of PI/128   float an, res, sres,;   for (an=0.0;an<(PI);an+=(PI/128))   {      //res1=fast_sin1(an);      res=fast_sin(an);      sres=sin(an);      printf ("AN=%5.3f sinfast=%5.3f sin=%5.3f\n",an,res,sres);   }   while(TRUE)      delay_cycles(1); }

I don't show a test for the cos, but this works exactly the same. Slightly slower.
 Display posts from previous: All Posts1 Day7 Days2 Weeks1 Month3 Months6 Months1 Year Oldest FirstNewest First
 All times are GMT - 6 Hours Page 1 of 1

 Jump to: Select a forum Software----------------General CCS C DiscussionCode LibraryEZ App Lynx Hardware----------------CCS ICD / Mach X / Load-n-Go
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum