import numpy as np import matplotlib.pyplot as plt from math import factorial #a) """ s[0] = 0 a[0] = x s[j] = s[j-1] + a[j-1] a[j] = -x**2/((2*j + 1)*2*j) * a[j-1] """ #b) def sin_Taylor(x, n): a0 = x s0 = 0 a = np.zeros(n+2) s = np.zeros(n+2) a[0] = a0 for j in range(1,n+2): s[j] = s[j-1] + a[j-1] a[j] = -x**2/((2*j + 1)*2*j) * a[j-1] return s[-1], abs(a[-1]) print(sin_Taylor(np.pi/2, 20)) #c) """ Taylor-rekke for h?nd: s[n+1] => s[3] = a[0] + a[1] + a[2] a[0] = x a[1] = -x**3 / 3! a[2] = x**5 / 5! """ def test_sin_Taylor(): tol = 1e-10 x = 0.5 expected = x - x**3/(factorial(3)) + x**5 / factorial(5) computed = sin_Taylor(x, 2)[0] assert abs(expected - computed) < tol test_sin_Taylor() #d) x_max = 4*np.pi """ x and y must be arrays, and we can use a nested loop; for every n value we loop through x, compute the Taylor series for each element in x, and fill the result into y. Then we plot y as a function of x for each n value. """ x = np.linspace(0,x_max,1001) y = np.zeros_like(x) for n in range(10): for i in range(len(x)): y[i] = sin_Taylor(x[i],n)[0] plt.plot(x,y,label=f'n={n}') plt.plot(x,np.sin(x),label='Exact') plt.axis([0,x_max,-2,2]) plt.legend() plt.show()