The sine function can be evaluated by the following infinite series: sin(x) = x
ID: 3765875 • Letter: T
Question
The sine function can be evaluated by the following infinite series: sin(x) = x – (x^3/3!) + (x^5/5!) – (x^7/7!) + · · · Write a function approx.sine in matlab that takes as input two parameters, x and threshold, to perform the following task. Starting with the simplest approximation sin(x) = x, add terms one at a time to improve this estimate until | (true – approximation)/ true | < threshold. Your function must return two output values: the approximate value of sin(x) and the number of terms that were needed to obtain this value subject to the desired error threshold.
The following is an example of function behavior for x = /5.
>> x = pi/5;
>> real = sin(x)
real =
0.5878
>> threshold = 0.001;
>> [approx terms] = approx_sine(x, threshold)
approx =
0.5878
terms =
2
>> threshold = 0.00001;
>> [approx terms] = approx_sine(x, threshold)
approx =
0.5878
terms =
3
Note that the terms value returned by the function only counts the number of terms added to the starting approximation of sin(x).
Explanation / Answer
function result = approx_sine(xrad, threshold)
%sin(x) = x – (x^3/3!) + (x^5/5!) – (x^7/7!) + · · ·
sinsum = xrad;
i = 3
terms = 1
realval = sin(xrad)
prevsign = 1
approx = (realval - sinsum)/realval
% if(approx < 0)
% approx = approx * -1
% end
while approx < threshold
prevsign = prevsign * -1
sinsum = sinsum + ( prevsign * (power(xrad, i) / factorial(i)))
i = i + 2
approx = (realval - sinsum)/realval
% if(approx < 0)
% approx = approx * -1
% end
end
terms = (i+1)/2
result = [sinsum terms]
end
x = pi/5;
threshold = 0.001;
[approx terms] = approx_sine(x, threshold)
threshold = 0.00001;
[approx terms] = approx_sine(x, threshold)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.