Script to compute how many terms you need to approximate sin(20) = 0.912945 to six decimal digits

I need to write a script that computes the minimum number of terms you need to approximate sin(20) = 0.912945 to six decimal digits, then prints "It takes n=1000 terms to approximate sin(20) = 0.912945 to six digits, the approximation is 0.9129451."
I already wrote a function to compute the sin(x) formula, the code for it is here:
function [] = sinQ4c(x, n)
x = input('Enter the value of x to computer sin(x): ');
n = input('Enter the number of n terms: ');
z = 1;
count = 0;
while z >= 1*(10^-3);
count = count + 1;
terms(count) = (-1)^(count+1)*(x^n)/factorial(n);
SINx = sum(terms);
n = n+2;
z = abs((sin(x)-SINx)/sin(x))*100;
end
disp(SINx)
end
I just can't seem to figure out how to do this part.

Answers (1)

Michael - I think that you have the right idea with the above code, but the use of n is not quite correct (especially how it is used in the Taylor series for sin(x)). You don't need to request the user to specify a value of n. The code is supposed to determine that based on the difference between the Taylor series expansion with k terms versus the expansion with k-1. (Also, x and n need not be inputs to the function as the user is then prompted for those same values.) Your could do the following instead
z = realmax;
n = 0;
sinTaylorSeries = 0;
sinTaylorSeriesP = z;
while z >= (10^-6)
n = n + 1;
sinTaylorSeries = sinTaylorSeries + (-1)^(n-1)*x^(2*n-1)/factorial(2*n-1)
z = abs(sinTaylorSeriesP-sinTaylorSeries);
sinTaylorSeriesP = sinTaylorSeries;
end
We continue iterating, and so continuing adding terms to the Taylor series, so long as the difference z is greater than 10^-6. In the above, the n will tell us how many terms have been used in the expansion. Note how we need to keep track of the Taylor series from the current iteration and the previous one, sinTaylorSeriesP, so that we can accurately compute the difference between the two on subsequent iterations.

2 Comments

Thanks! I understand it a bit better now, but I'm still not sure how to get it to show 6 decimal digits. When I run it I only get 4 decimal digits (0.9129) and n = 33.
Michael - type
format long
and then run your code. The above commands sets the Command Window output display format to that of the long fixed-decimal format (so you should see an answer similar to 0.912945290358371). See format for details.
To show six digits in your answer, do something like
fprintf('result=%.6f', sinTaylorSeries);

Sign in to comment.

Tags

Asked:

on 6 Feb 2016

Edited:

on 7 Feb 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!