Hi! I need help with a function with arrays.

1 visualizzazione (ultimi 30 giorni)
Hi! I need help with a function with arrays. I did a function that receive the n terms and the outputs are the relative error and the pi estimate value. But, I need to do but in the following way:
Instructions: Implement the equation in a function that receives the relative error willing to accept and return the user a vector with all values of π and other vector estimated with relative errors associated with each value of π. The equation is
pi/4= 1-1/3+1/5-1/7+1/9...- (Leibniz Equation)
The function that I have is the following:
%function
m=input('entre la cantidad de términos; ');
p=0;
for i=1: m
p=p-4*((-1)^(i-1)/(2*i*-1+1));
error=abs(pi-p);
if error <=0.01
break
end
end
disp('el numero de pi es;'); disp(p)
disp('El error cometido es;'); disp(error)
disp('La iteración final es:'); disp(i)
THANKS A LOT!
  1 Commento
Walter Roberson
Walter Roberson il 15 Ott 2016
Please do not use error as the name of a variable: error is the key MATLAB routine for triggering error conditions.

Accedi per commentare.

Risposta accettata

Walter Roberson
Walter Roberson il 15 Ott 2016
The 0.01 that you use needs to be replaced with a variable, as the problem statement requires that the acceptable relative error is an input.
You should be storing each p value as you go, something like
tolerance = 0.01;
p(1) = 0;
err(1) = pi;
for i=1: m
p(i+1) = p(i) -4*((-1)^(i-1)/(2*i*-1+1));
err(i+1) = abs(pi-p(i+1));
if err(i+1) <= tolerance
break
end
end

Più risposte (0)

Categorie

Scopri di più su Programming 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