3

I'm very new to Python, and am trying to approximate the sine function using this series.

My code looks like this:

import math
def sin(x,n):
sine = 0
for i in range(n):
    sign = (-1)**i
    sine = sine + ((x**(2.0*i-1))/factorial(2**i-1))*sign
return sine

This does not return the answer that I was hoping for, but I am very confused and can't find my mistake... or maybe I'm just going about this the wrong way entirely (as I said, I'm very new to python and to programming in general).

It seems similar to the program that I had to write a while ago to approximate pi given this series:

def piApprox(n):
pi = 0
for i in range(n):
    sign = (-1)**i
    pi = pi + 1.0/(2*i+1)*sign
return 4*pi

I don't know if that is useful in any way, but it's what I was trying to use that to figure out my sine method. Any help fixing this or pointing me in the right direction would be greatly appreciated!

user2141367
  • 81
  • 2
  • 2
  • 4

2 Answers2

5

The Taylor series for sin(x) is:

Taylor series for sin(x)

Comparing your code to that definition, these two parts have some errors:

x**(2.0*i-1)
factorial(2**i-1)

The minuses should be pluses, and the exponent in the factorial should be multiplication.

x**(2.0*i+1)
factorial(2*i+1)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
2

You can use the symbolic library SymPy to build your approximated function using Taylor series:

from sympy import sin
from sympy.abc import x

# creates a generator
taylor_series = sin(x).series(n=None)

# takes the number of terms desired for your generator
taylor_series = sum([next(taylor_series) for i in range(num_of_terms)])

# creates a function that calculates the approximated sine function
mysin = sympy.lambdify((x,), taylor_series)
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234