Advertisement
DeaD_EyE

taylor_series.py

Oct 3rd, 2019
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.19 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. """
  3. Task: Solve this formula
  4.  
  5. sinus(x)=x-((x**3)/3!)+((x**5)/5!)-((x**7)/7!)+...
  6.  
  7. https://en.wikipedia.org/wiki/Taylor_series
  8. """
  9.  
  10.  
  11. from math import factorial, pow, sin, tau
  12. from itertools import count, cycle
  13. from operator import add, sub, mul
  14. from functools import reduce
  15.  
  16. import matplotlib.pyplot as plt
  17.  
  18.  
  19. def pow(x, y):
  20.     """
  21.    simple own implementation of pow
  22.    """
  23.     return x ** y
  24.  
  25.  
  26. def factorial(x):
  27.     """
  28.    simple own implementation of factorial
  29.    functional style
  30.    """
  31.     return reduce(mul, range(2, x + 1), 1)
  32.  
  33.  
  34. def sinus(x, degree=21):
  35.     """
  36.    First overcomplicated idea. Just wanted to use itertools
  37.    as much I can.
  38.    """
  39.     if n == 1:
  40.         return x
  41.     y = 0
  42.     ops = cycle((add, sub))
  43.     for factor, op, _ in zip(count(3, step=2), ops, range(degree)):
  44.         y = op(y, pow(x, factor) / factorial(factor))
  45.     return x - y
  46.  
  47.  
  48. def sinus2(x, degree=21):
  49.     """
  50.    Straight forward implementation, which looks easier
  51.    and should run faster. The name tau is 2 * pi
  52.    The modulo operation makes it possible to use x < -2pi and x > 2pi
  53.    """
  54.     x %= tau
  55.     sign = -1
  56.     y = 0
  57.     for factor in range(3, degree + 1, 2):
  58.         y += sign * pow(x, factor) / factorial(factor)
  59.         sign *= -1
  60.     return x + y
  61.  
  62.  
  63. def cosine(x, degree=21):
  64.     """
  65.    Almost the same like sinus2
  66.    """
  67.     x %= tau
  68.     sign = -1
  69.     y = 0
  70.     for factor in range(2, degree + 1, 2):
  71.         y += sign * (pow(x, factor) / factorial(factor))
  72.         sign *= -1
  73.     return  1 + y
  74.  
  75.  
  76. def visualize(degree):
  77.     legend = []
  78.     base = [x / 1000 for x in range(-10_000, 10_000, 100)]
  79.     for n in degree:
  80.         legend.append(f'degree={n}')
  81.         plt.plot(base, [sinus(x, n) for x in base])
  82.     legend.append('math.sin(x)')
  83.     plt.plot(base, [sin(x) for x in base])
  84.     plt.legend(legend, loc='upper right', framealpha=0.2, fontsize=8)
  85.     plt.title('Taylor series')
  86.     plt.xlabel('x')
  87.     plt.ylabel('y')
  88.     plt.xlim(-10, 10)
  89.     plt.ylim(-10, 10)
  90.     plt.grid()
  91.     plt.savefig('Taylor series.png', dpi=300)
  92.     plt.show()
  93.  
  94.  
  95. if __name__ == '__main__':
  96.     visualize([1, 3, 5, 7, 9, 11, 13])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement