-
-
Save jacadzaca/0b76d75411566d506df3d8897204e00e to your computer and use it in GitHub Desktop.
compute sin using a taylor sereis and compare it with math.sin
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
#!/usr/bin/env python3 | |
# pip install matplotlib | |
import math | |
import matplotlib | |
import matplotlib.pyplot as plt | |
def float_range(end, start=0, step=0.1): | |
i = start | |
while i < end: | |
i += step | |
yield i | |
def nth_sin_derivative(n, a=math.pi/2): | |
if n % 4 in (2,3): | |
sign = -1 | |
else: | |
sign = 1 | |
if n % 2 == 0: | |
function = sin | |
else: | |
function = cos | |
return sign * function(a) | |
def sin(x, center=math.pi/2, term_count=5): | |
if x == math.pi/2: | |
return 1 | |
elif x == 0: | |
return 0 | |
else: | |
values = (((x - center)**i / math.factorial(i)) * nth_sin_derivative(i, a=center) for i in range(term_count)) | |
return sum(values) | |
def cos(x): | |
return sin((math.pi / 2) - x) | |
if __name__ == '__main__': | |
X = list(float_range(2*math.pi)) | |
Y = [math.sin(x) for x in X] | |
for i in range(1, 21): | |
Y_approx = [sin(x, term_count=i) for x in X] | |
fig, ax = plt.subplots() | |
#uncomment these to generate the graphs | |
#ax.plot(X, Y, color='C1') | |
#ax.scatter(X, Y_approx, color='C2') | |
#fig.savefig(f'figure{i}.png') | |
ax.bar(X, Y_approx, color='C2') | |
ax.bar(X, Y, color='C1') | |
fig.savefig(f'barplot{i}.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment