Write a user-defined function that solves for the cosine (radians) of an angle u
ID: 643828 • Letter: W
Question
Write a user-defined function that solves for the cosine (radians) of an angle using the Taylor series expansion shown below. The function name and arguments should be y = cosTaylor(x), where the input argument x is the angle in radians and the output argument y is the value for cos(x). The user defined function should contain a while loop that will continue to add elements to the series until the numerical approximation error is acceptable. When the approximation of error is equal to or less than .000001, then the equation has reached an acceptable value (the addition of another term will not significantly change the result). Error is calculated by the equation below, where Sn is the current term of the summation, and Sn-1 is the previous term of the summation:
Calculate cosTaylor for the following values of x:
a=0
b=1/4
c=2
Using MatLAb
Explanation / Answer
Matlab code for cosTaylor.
%Create a user-defined function
function y = cosTaylor(x)
a = 0;
E = 1;
n=0;
while E>=0.000001
sn = a;
a = a + ((-1)^(n)*x^(2*n))/factorial(2*n);
n = n+1;
E = abs((a-sn)/sn);
end
y = a;
end
Outputs:
>> cosTaylor(0)
ans = 1
>> cosTaylor(pi/6)
ans = 0.8660
>> cosTaylor(pi/3)
ans = 0.5000
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.