I need help with this function of estimate the value of PI
    1 vue (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
    Anthony Fuentes
 le 16 Oct 2016
  
    
    
    
    
    Modifié(e) : Walter Roberson
      
      
 le 16 Oct 2016
            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 commentaires
Réponse acceptée
  Walter Roberson
      
      
 le 16 Oct 2016
        
      Modifié(e) : Walter Roberson
      
      
 le 16 Oct 2016
  
      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 commentaires
Plus de réponses (0)
Voir également
Catégories
				En savoir plus sur Mathematics and Optimization dans Help Center et File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

