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!

