Write a Python program that uses a while loop to compute and print the cosine of
ID: 3668620 • Letter: W
Question
Write a Python program that uses a while loop to compute and print the cosine of an angle using the first 20 terms of the following series
cosx = 1 - ((x^2/2!)) + ((x^4/4!)) - ((x^6/6!))....
where x is in radians. Your program must input a value for x in degrees, convert it to radians and print the computed cosine of the given angle. You may use math.cos to check your answer, but do not use it in your solution!
Hint: Notice how the numerator and denominator change from iteration to iteration and apply a "rule" that will update the numerator and denominator at each iteration. Note that the numerator of each term is the numerator of the previous term multiplied by x 2 and also note the denominator of each term is the denominator of the previous term multiplied by the next two integers in the series. You should NOT re-compute the complete factorial at each step!
Constraints:
You must use while loops for all repetition in your solution to this problem, do not use for loops.
• Do not import or use any module functions to solve this problem
• Do not use the Python exponentiation operator (see Hint below)
• Do not construct or call any user-defined functions in your solution
Has to be in python
Explanation / Answer
the general term of a cosx series is (-1)(i) (x2i)/(2i)! , where i = 0 to inf
#######################################
sum = 0.0
def power(val,n):
mul = 1
i=0
while(i<n):
mul = mul*val
i = i +1
return mul
def fact(n):
mul = 1
i = 1
while (i < n+1):
mul = mul*i
i = i +1
return mul
x = some_value
i = 0
while (i<20):
sum+= power(-1,i)*power(x, 2*i)/fact(2*i)
i+=1
print sum
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.