user
Introduction

CORDIC is the name of an algorithm for calculating trigonometric, logarithmic and hyperbolic functions, named after its first application on an airborne computer (COordinate Rotation DIgital Computer) in 1959.
Unlike a Taylor expansion or polynomial approximation, it converges rapidly on machines with low computing and memory capacities: to calculate a tangent with 10 significant digits, it requires only 6 floating-point constants, and only additions, subtractions and digit shifts in its iterative part.

It is valid for angle values between 0 and π/2 only, but whatever the value of an angle, the calculation of its tangent can always be reduced to that of an angle between 0 and π/2, using trigonometric identities. Similarly, once you know the tangent, you can easily calculate the sine or cosine.

Pseudo code

```
constant θ[n] = arctan 10^(-n) // or simply 10^(-n) depending on floating point precision 
constant epsilon = 10^-12

function tan(alpha)            // 0 < alpha <= π/2 
  x = 1 ; y = 0 ; k = 0
  while epsilon < alpha
    while alpha < θ[k] 
       k++
    end loop
    alpha -= θ[k]
    x2 = x - 10^(-k)*y
    y2 = y + 10^(-k)*x
    x = x2 ; y = y2
  end loop
  return (y/x)
end function

```

Task

* Implement the CORDIC algorithm, using only the 4 arithmetic operations and right shifts in the main loop if possible.
* Use your implementation to calculate the cosine of the following angles, expressed in radians: -9, 0, 1.5 and 6

See also

CORDIC on Wikipedia
assistant
**Translation of**: XPL0

```
# 2023082 Raku programming solution

sub CORDIC ($A is copy) {

   my (\Ten, $K, $X, $Y) = ( 1, * * 1/10 ... * )[^6], 0, 1, 0;

   my \Tbl = < 7.853981633974480e-1 9.966865249116200e-2 9.999666686665240e-3 
               9.999996666668670e-4 9.999999966666670e-5 9.999999999666670e-6 0.0>;

   while $A > 1e-5 { 
      $K++ while $A < Tbl[$K];
      $A -= Tbl[$K];
      ($X,$Y) = $X - Ten[$K]*$Y, $Y + Ten[$K]*$X;
   }
   return $X, sqrt($X*$X + $Y*$Y)
}

say "Angle    CORDIC       Cosine       Error";
for <-9 0 1.5 6> { 
   my \result = [/] CORDIC .abs;
   printf "% 2.1f  "~"% 2.8f  " x 3~"\n", $_, result, .cos, .cos - result
}

```

Output:

Same as XPL0 or you may Attempt This Online!