Advertisement
regzarr

CORDIC method

Dec 5th, 2019
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 KB | None | 0 0
  1. #include<stdio.h>
  2. #include <math.h>
  3.  
  4. #define PI_OVER_6 0.523598776
  5.  
  6. double mycos(double theta, int n) {
  7.     double x, y, z;
  8.     // compute k
  9.     double k = 1;
  10.     for (int i = 0; i < n; ++i) {
  11.         k *= sqrt(1 + pow(2, -2 * i));
  12.     }
  13.    
  14.     x = 1/k;
  15.     y = 0;
  16.     z = theta;
  17.     double nextX, nextY, nextZ;
  18.     double alpha;
  19.     double measuredError = 0;
  20.    
  21.     for (int i = 0; i < n; ++i) {
  22.         alpha = atan(pow(2, -i));
  23.         measuredError = x - cos(PI_OVER_6);
  24.        
  25.         printf("x(%d) = %lf\n", i, x);
  26.         printf("y(%d) = %lf\n", i, y);
  27.         printf("z(%d) = %lf\n", i, z);
  28.         printf("alpha(%d) = %lf\n", i, alpha);
  29.        
  30.         printf("Measured error: %lf\n", measuredError);
  31.         if (z >= 0) {
  32.             nextX = x - (pow(2, -i) * y);
  33.             nextY = y + (pow(2, -i) * x);
  34.             nextZ = z - atan(pow(2, -i));
  35.         } else {
  36.             nextX = x + (pow(2, -i) * y);
  37.             nextY = y - (pow(2, -i) * x);
  38.             nextZ = z + atan(pow(2, -i));
  39.         }
  40.        
  41.         x = nextX;
  42.         y = nextY;
  43.         z = nextZ;
  44.     }
  45.     return nextX;
  46. }
  47.  
  48. int main() {
  49.     double piOver6 = 0.523598776;
  50.    
  51.     double theta = piOver6, result;
  52.     int n = 0;
  53.     while(1) {
  54.         //printf("cos(theta) = ?; type in theta: \n");
  55.         //scanf("%lf", &theta);
  56.         printf("type in n (number of iterations): \n");
  57.         scanf("%d", &n);
  58.        
  59.         printf("RESULT: %lf\n\n", mycos(theta, n));
  60.     }
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement