find magnitude of approximate percent relative error

24 visualizzazioni (ultimi 30 giorni)
I am asked to find 7 estimates of sin(x) and errors using a for loop.
I can get my code to run good for the 7 estimates and true error of each but im not sure how to separate the estimates apart to get the magnitude of approx. percent relative error. I put the equation for MAPRE for reference but im not sure how to write the 'sum' inside to give me each estimates MAPRE.
x=pi/5;
sum=0;
% using a for loop to find the first seven estimates of sin(x)
for k = 0:6;
sum = sum + (-1)^k*(x^(2*k+1)/factorial(2*k+1))
% finding magnitude of true error
f_exact = sin(pi/5); % True value
MagTrueerr = abs(sum - f_exact)
% finding magnitude of approximate percent relative error
MAPRE = abs((sum1-sum0)/sum1)*100
end
  2 Commenti
David Hill
David Hill il 21 Set 2019
Just make arrays for sum, MagTrueerr, and MAPRE that stores the answers during each loop.
Tiffany Lodge
Tiffany Lodge il 21 Set 2019
I dont completely understand, because if i put sum(k) to make sum an array. i get an error saying array indices need to be postive integers or logical values. is this not what you meant?

Accedi per commentare.

Risposte (1)

David Hill
David Hill il 21 Set 2019
a=(-1).^k.*(x.^(2*k+1)./factorial(2*k+1));
MagTrueerr=abs(cumsum(a)-f_exact);
MAPRE=100*MagTrueerr./cumsum(a);
No loops needed.
  5 Commenti
David Hill
David Hill il 21 Set 2019
It works. Make sure you preallocate a.
a=zeros(1,7);

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by