In: Computer Science
Write a program in python to calculate the value of cos(?) using its Taylor series expansion:
?2 ?4 ?6 ?8 cos(?)=1− + − + ...
The program should consist of the following functions:
a) Develop and test a cosCalc() function that receives as an argument, of type float, the value of the variable and returns the result as a float also. Include 20 terms maximum from the series, or until the value of a term is less than 1e-8. b) Write a main program to invoke the function and calculate and print the values of
2! 4! 6! 8!
?2?
cos (− ), cos(−?), and sin ( ).
`Hey,
Note: If you have any queries related to the answer please do comment. I would be very happy to resolve all your queries.
import numpy as np
def fact(n):
if(n<=1):
return 1;
return n*fact(n-1);
def cosCalc(x):
s=0;
for i in range(20):
t=(-1)**i*(x**(2*i))/fact(2*i);
s=s+t;
if(abs(t)<1e-8):
break;
return s;
def main():
print("cos(pi/4)=",cosCalc(np.pi/4.0));
print("cos(-pi)=",cosCalc(-np.pi));
main();
Kindly revert for any queries
Thanks.