Cos extension series with Python

So, I'm trying to find the value of cos(x)where x=1.2. I feel that the script I wrote should be fine, however the value I selected is incorrect. I.e; cos(1.2)=0.6988057880877979To 25terms when I have to go out: cos(1.2)=0.36235775.

I created a similar calculation program sin(1.2)that works great.

Calculation sin(1.2):

import math as m

x=1.2
k=1
N=25
s=x
sign=1.0

while k<N:
    sign=-sign
    k=k+2
    term=sign*x**k/m.factorial(k)
    s=s+term

print('sin(%g) = %g (approximation with %d terms)' % (x,s,N))

Now let's try to calculate cos(1.2):

import math as m

x=1.2
k=1
N=25
s=x
sign=1.0

while k<N:
    sign=-sign
    k=k+1
    term=sign*x**k/m.factorial(k)
    s=s+term

print(s)
+4
source share
2 answers

You do not have to set the initial amount in 1.2, but your representation of the extension

enter image description here

- , increment k 2. , , . ,

import math as m

x=1.2
k=0
N=25
s=0
sign=1.0

while k<N: 
    term=sign*x**(k)/m.factorial(k)
    s=s+term
    k += 2
    sign = -sign

print(s)

0.3623577544766735
+3

, , ( ^):

sum_over_n [(-1)**n * x ** (2 * n) / (math.factorial(2 * n))]
#                           ^^^^                     ^^^^

n -terms, - :

def cosine_by_series(x, terms):
    cos = 0
    for n in range(terms):
        cos += ((-1)**n) * (x ** (2*n)) / (math.factorial(2 * n))
    return cos
    # or simply:
    # return sum(((-1)**n) * (x ** (2*n)) / (math.factorial(2 * n)) for n in range(terms)

:

>>> cosine_by_series(1.2, 30)
0.3623577544766735
0

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


All Articles