Created
May 14, 2020 01:04
-
-
Save shirriff/caf8405ba9c2ff269c3e8440414b2c54 to your computer and use it in GitHub Desktop.
Demo of the 8087's CORDIC tangent algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
# 8087 tangent algorithm, from Implementing Transcendental Functions, R. Nave | |
atan_table = [math.atan(2 ** -i) for i in range(0, 17)] | |
def cordic_tan(z): | |
# Compute tan of angle z, using CORDIC | |
q = [] | |
# Break down z into sum of angles, where each angle is 0 or atan(2**-i) | |
# q holds corresponding 0 or 1 bits | |
for i in range(1, 17): | |
if z >= atan_table[i]: | |
z -=atan_table[i] | |
q.append(1) | |
else: | |
q.append(0) | |
# Approximate tan of remaining z (very small) | |
tg = (3 * z) / (3 - z * z) | |
# Create a (non-unit) vector with angle of the remaining z | |
# tan(remaining z) = y/x | |
y = tg | |
x = 1 | |
# Rotate the vector for each angle in the original sum of angles | |
# This will bring the vector back to the original angle z | |
# (Vector is also scaled, but that doesn't affect the tangent.) | |
for i in range(16, 0, -1): | |
if q[i - 1]: | |
y_tmp = y + x * 2**-i | |
x = x - y * 2**-i | |
y = y_tmp | |
# Angle of vector is now the original z | |
# So tan(z) = y/x | |
return y / x | |
# demo the function | |
z = 0 | |
while z < math.pi / 4: | |
print(z, cordic_tan(z), math.tan(z)) | |
z += 0.1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment