%
%---------------------------------------------------------------------  
% function [roundtrips] = FT_FFT_required_cavity_roundtrips(cavity, accuracy)
% 
% Matlab function to estimate the required number of roundtrips to
% compute the circulating power to the requested accuracy.
%
% cavity (structure):    cavity parameters and components 
%                        (see FT_init_cavity.m)
% accuracy (real):       requried accuracy (relative error) for power calculation
% 
% roundtrips (integer):  estimate for the number of roundtrips required
%
% Part of the SimTools package
% Andreas Freise, Jerome Degallaix 26.12.2009 afreise@googlemail.com
%---------------------------------------------------------------------  
%

% Description: Estimates required number of roundtrips to achieve requested
% Description: accuracy in computing the circulating power
% Keywords: estimate, required, accuracy, cavity, power

function [roundtrips] = FT_FFT_required_cavity_roundtrips(cavity, accuracy)
  
   R=1-cavity.Loss;
   
   % after Inf roundtrips the power is given by
   % P_total=P_in/(1-r)^2
   % after N roundtrips it is
   % P_N=P_in (1-r^{N+1))^2/(1-r)^2
   % with P_in the power transmitted into the cavity
   % So the relative error is
   % 1-P_N/P_total=1-(1-r^(N+1))^2 which should be smaller than accuracy.
   % This yields
   
   % roundtrips = ceil(log(1-sqrt(1-accuracy))/log(sqrt(R)))-1;
   
   % for accuracy<<1 we can simplify to
   
   roundtrips = 2*ceil(log(0.5*accuracy)/log(R));
   
   return;