CORDIC算法的C语言实现。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define PI 3.14159265358979
double mysin(double angle);
int main(void)
{
clock_t start, end;
printf("Using cordic:\n");
start = clock();
for (int i = 1; i < 90; i++)
{
printf("sin(%d) = %f\n", i, mysin(i * PI / 180));
}
end = clock();
printf("Time elapsed: %dms.\n", end - start);
printf("Using math.h\n");
start = clock();
for (int i = 1; i < 90; i++)
{
printf("sin(%d) = %f\n", i, sin(i * PI / 180));
}
end = clock();
printf("Time elapsed: %dms.\n", end - start);
system("pause");
return 0;
}
double mysin(double angle)
{ // angle in radian
int S = 0x40000000; //将所有数值缩放S倍
int target = (int)(angle * S);
int A[24] = {843314857, 497837829, 263043837, 133525159,
67021687, 33543516, 16775851, 8388437, 4194283, 2097149, 1048576, 524288,
262144, 131072, 65536, 32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128};
int x = 652032876;
int y = 0;
int xnew = 0, ynew = 0;
int Delta = 0; //旋转后的角度
for (int i = 0; i < 24; i++)
{
if (target > Delta) //当前角度小于目标角度
{ //逆时针旋转
xnew = x - (y >> i);
ynew = y + (x >> i);
Delta += A[i];
}
else //当前角度大于目标角度
{ //顺时针旋转
xnew = x + (y >> i);
ynew = y - (x >> i);
Delta -= A[i];
}
x = xnew;
y = ynew;
}
return (double)y / S;
}
实际上 (double) x/S就是余弦值。