finding cosine using python

橙三吉。 提交于 2019-12-12 01:06:09

问题


I must write a function that computes and returns the cosine of an angle using the first 10 terms of the following series: cosx = 1 - (x**2)/2! + (x**4)/4! - (x**6)/6!....

I can't use the factorial function, but i can use the fact that if the previous denominator was n!, the current denominator would be n!(n+1)(n+2). I'm trying to use an accumulator loop, but i'm having a hard time with the fact that it alternates from positive to negative and also having trouble with the denominator.

This is what I have thus far. Any help with the denominator and accumulator loop?

def factorial(x):

    if(x == 0): 
        return 1
    return x * factorial(x-1)


def cosine(angle):

    cosx = 1
    sign = -1
    for i in range(2, 20, 2):
        cosx = cosx + (sign*(angle**i))/factorial(i)
        sign = -sign
    return cosx

回答1:


Maybe something like this:

#! /usr/bin/python3.2

def cos (a):
    d = 1
    c = 1
    for i in range (2, 20, 2):
        d *= i * (i - 1)
        sign = -1 if i % 4 else 1
        print ('adding {} * a ** {} / {}'.format (sign, i, d) )
        c += sign * a ** i / d
        print ('cosine is now {}'.format (c) )
    return c

cos (1.0)

Basically d (as in Denominator) is your accumulator.




回答2:


Note: If you are using Python2.x, you should use

from __future__ import division

as the first line of the file


One way is to alternate the sign like this

def cos(angle):
    sign = -1
    cosx = 1
    for i in range(2,20,2):
         cosx += sign*(x**i)/(i)
         sign = -sign

You'll still need to get the factorial part correct

Here is a simpler version that calculates each term based on the previous one.

def cos(x):
    res = 0
    term = 1
    for i in range(1, 20, 2):
        res += term
        term *= -x * x/ i /(i + 1)
    return res



回答3:


Why not make a function for factorial? (I added an optional parameter for repetitions):

EDIT:

as per a comment, here's a "learning" factorial function that will make sure not to recalculate any values (granted this will only work up to 199!, I'm assuming there will never be more than 99 repetitions with the cos function since it will probably throw an overflow error around 90 already):

facts = [0]*200
facts[0] = 1
def factorial(x): 
    if(facts[x] != 0): return facts[x]
    return x * factorial(x-1)

def cos(x, reps=10):
    final_val = 1
    neg = -1
    for n in range(2, reps*2, 2):
        final_val += neg*(x**n)/factorial(n)
        neg *= -1
    return final_val

print cos(3.14/2)



回答4:


For calculating series, use the power of list comprehensions.

In [1]: a = range(1,11)

In [2]: a
Out[2]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The mul function multiplies the elements of the list it is given:

In [3]: def mul(r):
   ...:     rv = 1
   ...:     for j in r:
   ...:         rv *= j
   ...:     return rv
   ...: 

Now you can generate the factorials:

In [7]: b = [mul(a[:i]) for i in a]

In [8]: b
Out[8]: [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

To pick the right elements from the lists;

In [10]: a[1::2]
Out[10]: [2, 4, 6, 8, 10]

In [11]: b[1::2]
Out[11]: [2, 24, 720, 40320, 3628800]

To generate the plusses and minuses:

In [12]: [(-1)**k for k in a[:5]]
Out[12]: [-1, 1, -1, 1, -1]

Combine all the elements;

In [14]: data = zip(a[1::2], b[1::2], [(-1)**k for k in a[:5]])

Then do the calculation for a certain x;

In [21]: x = 12

In [22]: sum([s*x**t/float(b) for t, b, s in data])
Out[22]: -9753.737142857142


来源:https://stackoverflow.com/questions/20202922/finding-cosine-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!