In: Computer Science
The cos(x) function can be represented in a Taylor series shown below:
Write a Matlab program, and use a while loop, to calculate cos(150) (the input is in degrees) by adding terms of the series and stopping when the absolute value of the term that was added last is smaller than 0.0001.
Make sure to make the required degree <-> radian conversions.
Use fprintf to print the cos(150) (up to 2 decimal places) and the number of terms used to calculate it. Also, calculate and print the cos(150) using matlab's built-in function cosd. (Your code and the cosd function should return the same values).
Code Screenshot :
Executable Code:
result = 1;
angle = 150*(pi/180);
numerator = angle*angle;
denominator = 2;
sign = -1;
degree = 2;
count = 1;
while(numerator/denominator >= 0.0001)
result = result + sign*(numerator/denominator);
sign = -sign;
numerator = numerator * angle * angle;
denominator = denominator * (degree+1) * (degree +
2);
degree = degree + 2;
count = count + 1;
end
fprintf("%.2f is the value of cos(150) by Taylor series and
total of %d terms is used\n",result,count);
fprintf("%.2f is the value of cos(150) by cosd in-build
function\n",cosd(150));
Sample Output :
Please comment
below if you have any queries.