35 lines
669 B
Python
35 lines
669 B
Python
|
import numpy as np
|
||
|
import matplotlib.pyplot as plt
|
||
|
|
||
|
def sin_approx_factory(n):
|
||
|
def factorial(k):
|
||
|
result = 1
|
||
|
for i in range(1, k + 1):
|
||
|
result *= i
|
||
|
return result
|
||
|
|
||
|
|
||
|
def sin(x):
|
||
|
result = 0
|
||
|
for i in range(0, n + 1):
|
||
|
#print("+ (-1)**{} * x**{} / {} ".format(i, 2*i + 1, factorial(2*i + 1)), end = "")
|
||
|
result += (-1)**(i) * x**(2*i + 1) / factorial(2*i + 1)
|
||
|
#print()
|
||
|
return result
|
||
|
return sin
|
||
|
|
||
|
|
||
|
X = np.arange(-4, 4, 0.01)
|
||
|
plots = list()
|
||
|
|
||
|
p0, = plt.plot(X, np.sin(X), label="sin(x)")
|
||
|
plots.append(p0)
|
||
|
|
||
|
for i in range(5):
|
||
|
p, = plt.plot(X, sin_approx_factory(i)(X), label="approx({})".format(i))
|
||
|
plots.append(p)
|
||
|
|
||
|
plt.legend(handles=plots)
|
||
|
plt.show()
|
||
|
|