# Trigonometric functions using CORDIC algorithm (Python)

This program is a code dump.
Code dumps are articles with little or no documentation or rearrangement of code. Please help to turn it into a literate program. Also make sure that the source of this code does consent to release it under the MIT or public domain license.

See CORDIC article on Wikipedia for an explanation of the algorithm.

```<<cordic.py>>=
#!/usr/bin/python
from __future__ import division
from math import atan,pi,sqrt
import sys
# Calculate the arc Tan table once
ArcTanTable = []
for i in range(2048):
ArcTanTable.append(    atan( 2.0**(-1 * i) )    )
# Calculate the scaling factor K once
KN = []
value = 1.0
for i in range(2048):
value = value * sqrt(  1.0 + 2.0**(-2 * i)  )
KN.append(1.0 / value)
def CORDIC_function(degrees,iterations = 8):
# convert from degrees into radians
beta = degrees * pi / 180.0
# ensure that iterations is not greater than 2048
if iterations > 2048:
iterations = 2048
# Calculate the sine and cosine values using CORDIC algorithm
Vx,Vy = 1.0 , 0.0
for i in range(iterations):
if beta < 0:
Vx,Vy = Vx + Vy * 2.0**(-1 * i)  ,  Vy - Vx * 2.0**(-1 * i)
beta = beta + ArcTanTable[i]
else:
Vx,Vy = Vx - Vy * 2.0**(-1 * i)  ,  Vy + Vx * 2.0**(-1 * i)
beta = beta - ArcTanTable[i]
# Multiply by the scaling factor K
Vx,Vy = Vx * KN[iterations - 1] , Vy * KN[iterations - 1]
return (Vx,Vy,KN[iterations - 1])
if __name__ == '__main__':
if len(sys.argv) == 2:
deg  = float(sys.argv)
iter = 8
elif len(sys.argv) == 3:
deg  = float(sys.argv)
iter = int(sys.argv)
else:
print "using default values of 17 degrees and 8 iterations"
deg  = 17.0
iter = 8
(sine,cosine,K)=CORDIC_function(deg,iter)
print "K = %14.12f" % (K)
print "Sin(%4.1f) = %14.12f  and  Cos(%4.1f) = %14.12f" % (deg,sine,deg,cosine)
```