I need help with this function of estimate the value of PI
    조회 수: 1 (최근 30일)
  
       이전 댓글 표시
    
I need to do the following:
Implement the equation pi/4= 1-1/3+1/5-1/7+1/9...- (Leibniz Equation) in a function that receives the relative error willing to accept and return the user a vector with all values of π (estimations) and other vector with relative errors associated with each value of π.
But, I have the following function (below) and I need to transform it in the desire function. I don't know is this is correct. Can you help me please? I'm a premier in this, and an university's student but my concentration is in Chemical Engineering and that is very difficult for me!. Thanks a lot.
%function:
function[p,err,i]=PI2function(m)   % As you see m is the terms. But, I need that the function give me the terms and not to put them, only put the error that I want to accept (input). 
p=zeros([1 m]);       %This function is in Arrays
err=zeros([1 m]);      %err is the relative error  and p=is the estimated value of pi with that equation.
tolerance = 0.01;    % the output of the function are the terms, the relative error associated with each pi value, and the estimated pi value (the last one in Arrays)
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
채택된 답변
  Walter Roberson
      
      
 2016년 10월 16일
        
      편집: Walter Roberson
      
      
 2016년 10월 16일
  
      In this case, do not pre-allocate your arrays: let them grow with each iteration.
Your input parameter to the function should be tolerance rather than m. You do not need m in your code at all.
Change your for loop to be a while loop:
   i = 1;
   while true
     ...
     if condition is true
       break;
     end
     i = i + 1;
   end
Keep in mind, though, that the tolerance they give might be more than pi itself, so you might not need any iterations.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
				Help Center 및 File Exchange에서 Mathematics and Optimization에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

