Write a MATLAB program that determines cos (x) using the Taylor series expansion.

71 visualizzazioni (ultimi 30 giorni)
The Taylor series expansion for cos(x) is: cos(x)=1-x^2/2!+x^4/4!-x^6/6!+... =
(-1)^n/(2n)n!(x^2n)
n=0
where x is in radians. Write a MATLAB program that determines cos (x) using
the Taylor series expansion. The program asks the user to type a value for an
angle in degrees. Then the program uses a loop for adding the terms of the
Taylor series. If an is the nth term in the series, then the sum Sn of the n terms
is sn = sn-1 + an . In each pass calculate the estimated error E given by
E = abs(Sn-Sn-1/Sn-1)· Stop adding terms when E<=0.000001. The program displays the value of cos(x). Use the program for calculating:
(a) cos(35°) (b) sin(125°)
Compare the values with those obtained by using a calculator.
so far i have the following but it is not working.
A = input('Enter the value for an angle in degrees = ');
n=1; an = 1; Sn = Sn-1+an;
while E <= 0.000001
an = cos(35)/factorial(n);
Sn = Sn-1 + an
n = n+1;
end
if n <= 0.000001
disp('stop')
fprintf('Sn - Sn-1/Sn(%f) = %f', cos,Sn)
end

Risposta accettata

James Tursa
James Tursa il 8 Apr 2015
Modificato: James Tursa il 8 Apr 2015
Sn-1 is not meant to be typed in literally as you have done. It is meant to be the previous value of Sn. Also, x is required to be in radians for the series. Taking your code and correcting some of the setup details:
A = input('Enter the value for an angle in degrees = ');
x = A * pi / 180; % Convert the input to radians
n = 0; % First value of n
an = 1; % First term in the series
Sn = an; % First sum of the terms
E = inf; % Some arbitrary big value
while E > 0.000001 % While the estimated error is BIGGER than tolerance
n = n + 1; % Increment n
an = (insert code here for the nth term); % Next term in the series
E = abs(an/Sn); % Estimated error
Sn = Sn + an; % Add nth term into the sum
end
I have left it to you to code up the nth term.

Più risposte (0)

Categorie

Scopri di più su Mathematics in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by