# -*- coding: utf-8 -*-
"""Serie_de_Taylor_en_Python.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1-k9zbpEj8QcH3ncAcQAePCHC28Kuz46w

<a href="https://colab.research.google.com/github/joanby/calculo/blob/master/Serie_de_Taylor_en_Python.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# Serie de Taylor en Python

$$e^x = \sum_{k=0}^n \frac{x^k}{k!}$$
"""

import math

math.factorial(3)

x = 2
e_2 = x**0/math.factorial(0)+x**1/math.factorial(1)+x**2/math.factorial(2)+x**3/math.factorial(3)+x**4/math.factorial(4)
print(e_2)

print(math.exp(2))

def func_e(x, n):
  e_value = 0
  for k in range(n): #0, 1, 2, 3, 4
    e_value += x**k/math.factorial(k)
  return e_value

func_e(x = 2, n = 10)

func_e(5, 7)

x = 5
eps = 1e-6
for i in range(1, 200):
  e_app = func_e(x, i)
  e_exa = math.exp(x)
  e_err = abs(e_app - e_exa)
  if e_err < eps:
    break

print(f"Término {i}: Valor de Serie de Taylor = {e_app}, Valor real = {e_exa}, Error = {e_err}")



"""$$\cos(x) = \sum_{k=0}^n (-1)^k \frac{x^{2k}}{(2k)!}$$"""

def func_cos(x, n):
  cos_value = 0
  for k in range(n):
    coef = (-1)**k
    num = x**(2*k)
    den = math.factorial(2*k)
    cos_value += coef*num/den
  return cos_value

angle = math.radians(45)
print(func_cos(angle, 7))

math.cos(angle)

# Commented out IPython magic to ensure Python compatibility.
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline

angles = np.arange(-2*np.pi, 2*np.pi, 0.1)
p_cos = np.cos(angles)

fig, ax = plt.subplots()
ax.plot(angles, p_cos)

for n in range(1, 7):
  t_cos = [func_cos(angle, n) for angle in angles]
  ax.plot(angles, t_cos)

fig.set_size_inches(10,6)

ax.set_ylim([-7,5])

legend_list = ["Función cos(x)"]
for n in range(1, 7):
  legend_list.append(f"Pol. Taylor de grado {n}")
ax.legend(legend_list, loc = 3)

plt.show()

