Python Forum
A program to define sine function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A program to define sine function
#2
You can improve the code by using the relation that exists between two consecutive terms of the series, thus avoiding the computation of high powers of x and factorials
from itertools import count, islice
import math

def sine_terms(x):
    t = x
    f = -x ** 2
    for n in count(3, 2):
        yield t
        t *= f /((n-1) * n)
        
def sine(x, n):
    return sum(islice(sine_terms(x), n))

if __name__ == '__main__':
    print(sine(6, 25), math.sin(6))
Output:
-0.2794154981989254 -0.27941549819892586
There is necessarily an error for large values of x because the sine function is not a polynomial. You could find online estimates for the remainder of the series, for example here is an estimate for the remainder of the exponential series, which should work also for the sine series (I haven't checked the estimate). In fact, for the sine series you can get an easy bound for the error by using the Lagrange remainder of the Taylor formula.
Reply


Messages In This Thread
A program to define sine function - by mohanp06 - Aug-17-2020, 06:19 PM
RE: A program to define sine function - by Gribouillis - Aug-18-2020, 06:47 AM
RE: A program to define sine function - by mohanp06 - Aug-19-2020, 07:07 AM
RE: A program to define sine function - by mohanp06 - Aug-25-2020, 06:16 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020