Advertisement
makispaiktis

Taylor approach of a function

Sep 23rd, 2020 (edited)
1,410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. # I will try to approach a function with a Taylor series that has N-rank (3-rank here)
  2. # My function will be:
  3. # f(x) = sin(x) + 2 * ln(x+1) - 3 * x ^ 3 in the interval [0, 4*pi]
  4. from math import pi, sin, cos, log
  5. from matplotlib import pyplot as plt
  6.  
  7. def f(x):
  8.     return sin(x) + 2 * log(x+1) - 3 * x**3
  9.  
  10. def df(x):
  11.     return cos(x) + 2 / (x+1) - 9 * x**2
  12.  
  13. def d2f(x):
  14.     return - sin(x) - 2 / (x+1)**2 - 18 * x
  15.  
  16. def d3f(x):
  17.     return - cos(x) + 4 / (x+1)**3 - 18
  18.  
  19. def taylorF(x, center):
  20.     return f(center) + df(center) * (x-center) + 1/2 * d2f(center) * (x-center)**2 + 1/6 * d3f(center) * (x-center)**3
  21.  
  22.  
  23. # MAIN FUNCTION
  24. x = list()
  25. counter = 0
  26. while counter <= 4*pi:
  27.     x.append(counter)
  28.     counter += pi / 100
  29.  
  30. centers = list(range(0, 11, 2))
  31. for center in centers:
  32.     function = list()
  33.     taylor = list()
  34.     for elementX in x:
  35.         function.append(f(elementX))
  36.         taylor.append(taylorF(elementX, center))
  37.     plt.plot(x, function, label="Function")
  38.     plt.plot(x, taylor, label="Taylor")
  39.     plt.title("Center = " + str(center))
  40.     plt.legend()
  41.     plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement