Clear Filters
Clear Filters

Hi! I need help with a function with arrays.

1 view (last 30 days)
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 Comment
Walter Roberson
Walter Roberson on 15 Oct 2016
Please do not use error as the name of a variable: error is the key MATLAB routine for triggering error conditions.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 15 Oct 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

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!