Finding Cosine Using Python
Solution 1:
Maybe something like this:
#! /usr/bin/python3.2
def cos(a):
d =1c=1for i inrange(2,20,2):
d *= i *(i -1)sign=-1if i % 4else1
print ('adding {} * a ** {} / {}'.format (sign, i, d))c+=sign* a ** i / d
print ('cosine is now {}'.format (c))returnccos(1.0)
Basically d
(as in Denominator) is your accumulator.
Solution 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 =1for i inrange(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.
defcos(x):
res = 0
term = 1for i inrange(1, 20, 2):
res += term
term *= -x * x/ i /(i + 1)
return res
Solution 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] = 1deffactorial(x):
if(facts[x] != 0): return facts[x]
return x * factorial(x-1)
defcos(x, reps=10):
final_val = 1
neg = -1for n inrange(2, reps*2, 2):
final_val += neg*(x**n)/factorial(n)
neg *= -1return final_val
print cos(3.14/2)
Solution 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
Post a Comment for "Finding Cosine Using Python"