Hi! I need help with a function with arrays.

조회 수: 1 (최근 30일)
Anthony Fuentes
Anthony Fuentes 2016년 10월 15일
답변: Walter Roberson 2016년 10월 15일
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
Walter Roberson
Walter Roberson 2016년 10월 15일
Please do not use error as the name of a variable: error is the key MATLAB routine for triggering error conditions.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2016년 10월 15일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by