function x = lyngby_idf_chi2(r, F)

% lyngby_idf_chi2      - Invers X^2 distribution function
%
%	function x = lyngby_idf_chi2(r, F)
%
%       Input:  r   Degrees of freedom
%               F   Percentile (Optional, default 0.95)
%
%       Output: x   Invers value
%
%	Uses bisection with calls to lyngby_cdf_chi2
%
%       See also: lyngby_cdf_chi2

% cvs : $Id: lyngby_idf_chi2.m,v 1.1 1998/03/17 17:47:25 fnielsen Exp $
%       $Revision: 1.1 $

    MAXITER = 100;

    if nargin < 2
      F = 0.95;
    end
    

    if 1==1
      x1 = 0.5;
      x2 = 100;
      for e = 1:MAXITER
	x = (x1+x2)/2;
	Fiter = lyngby_cdf_chi2(x,r);
	if Fiter < F
	  x1 = x;
	else
	  x2 = x;
	end
      end
    else
      if r > 5
	if F == 0.9
	  z = 1.282;
	elseif F == 0.95
	  z = 1.645;
	elseif F == 0.975
	  z == 1.96;
	elseif F == 0.99
	  z = 2.326;
	elseif F == 0.995
	  z = 2.576;
	elseif F == 0.999
	  z = 3.090;
	else
	  error('The test cannot compute with the value of F');
	end
	x = r * (1 - 2/(9*r) + z * sqrt(2/(9*r))).^3; 
      else
	error('Sorry, not so approximate with such low DOF');
      end
    end











