Created
October 22, 2020 01:10
-
-
Save ritobanrc/dab406020d8a3131a88357478ab29c21 to your computer and use it in GitHub Desktop.
A surprisingly good recursive approximation of sin and cos using double angle theorem.
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
from math import sqrt, pi, sin, cos | |
def my_sin(x): | |
if x < 0.01: | |
return x | |
return 2 * my_sin(x/2) * my_cos(x/2) | |
def my_cos(x): | |
if x < 0.01: | |
s = my_sin(x) | |
return sqrt(1 - s * s) | |
s = my_sin(x / 2) | |
c = my_cos(x / 2) | |
return c * c - s * s | |
for x in range(0, 361, 30): | |
angle = x * pi / 180 | |
mine_sin = my_sin(angle) | |
actual_sin = sin(angle) | |
sin_error = (mine_sin - actual_sin)/max(actual_sin, 0.01) * 100 | |
mine_cos = my_cos(angle) | |
actual_cos = cos(angle) | |
cos_error = (mine_cos - actual_cos)/max(actual_cos, 0.01) * 100 | |
print(f"Angle: {x}, My Sin: {mine_sin:.5f}, Actual Sin: {actual_sin:.5f}, Sin Error: {sin_error:.5f}% My Cos: {mine_cos:.5f}, Actual Cos: {actual_cos:.5f}, Cos Error: {cos_error:.5f}%") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment