Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- """
- Task: Solve this formula
- sinus(x)=x-((x**3)/3!)+((x**5)/5!)-((x**7)/7!)+...
- https://en.wikipedia.org/wiki/Taylor_series
- """
- from math import factorial, pow, sin, tau
- from itertools import count, cycle
- from operator import add, sub, mul
- from functools import reduce
- import matplotlib.pyplot as plt
- def pow(x, y):
- """
- simple own implementation of pow
- """
- return x ** y
- def factorial(x):
- """
- simple own implementation of factorial
- functional style
- """
- return reduce(mul, range(2, x + 1), 1)
- def sinus(x, degree=21):
- """
- First overcomplicated idea. Just wanted to use itertools
- as much I can.
- """
- if n == 1:
- return x
- y = 0
- ops = cycle((add, sub))
- for factor, op, _ in zip(count(3, step=2), ops, range(degree)):
- y = op(y, pow(x, factor) / factorial(factor))
- return x - y
- def sinus2(x, degree=21):
- """
- Straight forward implementation, which looks easier
- and should run faster. The name tau is 2 * pi
- The modulo operation makes it possible to use x < -2pi and x > 2pi
- """
- x %= tau
- sign = -1
- y = 0
- for factor in range(3, degree + 1, 2):
- y += sign * pow(x, factor) / factorial(factor)
- sign *= -1
- return x + y
- def cosine(x, degree=21):
- """
- Almost the same like sinus2
- """
- x %= tau
- sign = -1
- y = 0
- for factor in range(2, degree + 1, 2):
- y += sign * (pow(x, factor) / factorial(factor))
- sign *= -1
- return 1 + y
- def visualize(degree):
- legend = []
- base = [x / 1000 for x in range(-10_000, 10_000, 100)]
- for n in degree:
- legend.append(f'degree={n}')
- plt.plot(base, [sinus(x, n) for x in base])
- legend.append('math.sin(x)')
- plt.plot(base, [sin(x) for x in base])
- plt.legend(legend, loc='upper right', framealpha=0.2, fontsize=8)
- plt.title('Taylor series')
- plt.xlabel('x')
- plt.ylabel('y')
- plt.xlim(-10, 10)
- plt.ylim(-10, 10)
- plt.grid()
- plt.savefig('Taylor series.png', dpi=300)
- plt.show()
- if __name__ == '__main__':
- visualize([1, 3, 5, 7, 9, 11, 13])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement