0

I am trying to implement sine function as Taylor Series approximation. I can't get a reasonable result with Taylor Series approximation form. I don't understand why.

Result is: sine with Taylor Series Approximation

and my code in Python is here:

import numpy as np
import matplotlib.pyplot as plt
import functools
f_reduce = functools.reduce

pow = np.power

from math import factorial

def f(t):
    return 2*t + np.pi / 2

# sine function in Taylor series form
def t_sin(t):
    def inner(n):
        return pow(-1, n) * pow(t, 2*n + 1) / factorial(2*n + 1)
    return f_reduce( lambda x,y: x + y, [ inner(step) for step in range(80) ] )

time = np.arange(-10*np.pi, 10 * np.pi, 0.1)
# x = np.sin(f(time))
x = t_sin(f(time))

plt.plot(time, x)
plt.show()

What's wrong with my code? Am I missing something?

cs95
  • 379,657
  • 97
  • 704
  • 746
safakeskin
  • 628
  • 5
  • 16
  • What does the plot look like if you limit the y axis to reasonable values? – mkrieger1 Feb 17 '19 at 21:11
  • @mkrieger1 According to formula, it should has to go until infinity. But factorial results become very big after a point (https://stackoverflow.com/q/16174399/6013366). So I chose 80 as the highest number, considering it as infinity :)) – safakeskin Feb 17 '19 at 21:11
  • and formula can be seen here http://people.math.sc.edu/girardi/m142/handouts/10sTaylorPolySeries.pdf – safakeskin Feb 17 '19 at 21:12
  • Well for `n` = 80 you are already calculating `factorial(161)`. Maybe you should start with `n` = 1, 2, 3, etc. and see what happens. – mkrieger1 Feb 17 '19 at 21:14
  • @mkrieger1 sine is a periodical function, so, whether we limit it or not, it should give same results for two points apart from each other with a constant time (period, 2*pi for sine), something similar to above plot (the one with Euler formula) – safakeskin Feb 17 '19 at 21:15
  • 1
    Please try it first before dismissing it. You're not plotting `sin`, you're plotting a sum of polynomials which *approximate* a sine curve for x values *close to 0*. For x values away from 0, the curve deviates from a sine curve considerably. You're expecting y values from -1 to 1, so you're not going to see anything if the plot range goes to 1e11. – mkrieger1 Feb 17 '19 at 21:16
  • @mkrieger1 you are right, actually everyting was correct. I am sorry for seen like dismissing, I was trying it actually but just wrote comment before trying. I am really sorry. Thank you! – safakeskin Feb 17 '19 at 21:21

1 Answers1

0

Thanks to @mkrieger , there were no problem with function but ranges were very stupid. Now, it actually looks like this:

enter image description here

Thank you @mkrieger ! :))

safakeskin
  • 628
  • 5
  • 16