Need help approximating a sinusoidal function in python using the Taylor series

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

My code is as follows:

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 I was hoping for, but I am very confused and cannot find my mistake ... or maybe I'm just completely wrong (as I said, m is very new for python and for programming in general).

It looks like a program that I had to write some time ago in order to get closer to the pi specified in 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 how useful this is anyway, but this is what I tried to use to determine my sinusoidal method. Any help correcting this or pointing me in the right direction would be greatly appreciated!

+3
source share
2 answers

The Taylor series for sin (x) is:

Taylor series for sin (x)

Comparing your code with this definition, these two parts have some errors:

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

Cons should be pluses, and the exponential in factorial should be multiplication.

 x**(2.0*i+1) factorial(2*i+1) 
+4
source

You can use the SymPy symbolic library to create your approximable function using the 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) 
+1
source

Source: https://habr.com/ru/post/1260338/


All Articles