Hi I am trying to write a code that finds approximations of sine and cosine using the equations below with a given value of theta in degrees basically as a novice programmer i am having trouble setting upa a while loop for the expansions. Also can you guys please quote sources(books,web pages, etc.) for a beginner programmer in python for syntax and basic concepts.

cos(x)= 1- x2/2! + x4/4! - x6/6! + ..

sin(x)= x - x3/3! + x5/5! - x7/7! + ..

Thanks in advance.

Dani AI

Generated

As asked: the practical bits are (1) evaluate the series in radians, (2) reduce the angle so the series converges quickly, and (3) avoid recomputing factorials/powers on every term. ' suggestion to read the Python tutorial is a good place to learn syntax, and 's degrees/radians hint is exactly why the conversion step is needed. 's pointer about factorial/pow is useful for a straightforward translation, but a recurrence is both simpler and faster.

Compute terms iteratively: start sine with term = x and cosine with term = 1.0, then update each term from the previous one by multiplying by -x*x and dividing by two consecutive integers (this reuses the previous factorial/power work). Stop when abs(term) drops below your chosen tolerance or after a safe maximum iteration count. Also reduce the input angle (for example map degrees -> radians, then reduce into the principal range like [-pi, pi]) before the loop to improve speed and numeric stability.

Example implementation (compact, no factorial/pow calls):

def sin_cos_from_degrees(theta_deg, eps=1e-12, max_iter=50):
    from math import pi
    x = theta_deg * pi / 180.0
    x = ((x + pi) % (2*pi)) - pi

    # sine (term = x, then update)
    s = term = x
    k = 1
    while abs(term) > eps and k < max_iter:
        term *= -x*x / ((2*k)*(2*k+1))
        s += term
        k += 1

    # cosine (term = 1, then update)
    c = term = 1.0
    k = 1
    while abs(term) > eps and k < max_iter:
        term *= -x*x / ((2*k-1)*(2*k))
        c += term
        k += 1

    return s, c

Quick tips: compare against the library sin/cos to pick a sensible eps (1e-12 is usually fine for double precision), reduce large inputs by modulo 360 before converting, and cap iterations to avoid infinite loops. This pattern is efficient and easy to read while giving good accuracy for learning purposes.

Recommended Answers

All 3 Replies

I suggest the official python tutorial to start with.

Hint, use math.pow() and math.factorial()
so
x4/4!
will be
math.pow(x, 4)/math.factorial(4)

Module math also has:
math.degrees(x) converts angle x from radians to degrees.
math.radians(x) converts angle x from degrees to radians.

You can get a good free online book here:
http://www.greenteapress.com/thinkpython/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.