/*							incbi()
 *
 *      Inverse of imcomplete beta integral
 *
 *
 *
 * SYNOPSIS:
 *
 * double a, b, x, y, incbi();
 *
 * x = incbi( a, b, y );
 *
 *
 *
 * DESCRIPTION:
 *
 * Given y, the function finds x such that
 *
 *  incbet( a, b, x ) = y.
 *
 * the routine performs up to 10 Newton iterations to find the
 * root of incbet(a,b,x) - y = 0.
 *
 *
 * ACCURACY:
 *
 *                      Relative error:
 *                x     a,b
 * arithmetic   domain  domain  # trials    peak       rms
 *    DEC       0,1     0,100      2500    2.9e-13   5.9e-15
 *    IEEE      0,1     0,100      5000    8.3e-13   1.7e-14
 *
 * Larger errors were observed for a near zero and b large.
 */


/*
Cephes Math Library Release 2.2:  July, 1992
Copyright 1984, 1987, 1992 by Stephen L. Moshier
Direct inquiries to 30 Frost Street, Cambridge, MA 02140
*/

#include "mconf.h"

extern double MACHEP, MAXNUM, MAXLOG, MINLOG;

double incbi( aa, bb, yy0 )
double aa, bb, yy0;
{
double a, b, y0;
double d, y, x, x0, x1, lgm, yp, di;
int i, n, rflg;
double incbet();
double ndtri(), exp(), fabs(), log(), sqrt(), lgam();


if( yy0 <= 0 )
	return(0.0);
if( yy0 >= 1.0 )
	return(1.0);

/* approximation to inverse function */

yp = -ndtri(yy0);

if( yy0 > 0.5 )
	{
	rflg = 1;
	a = bb;
	b = aa;
	y0 = 1.0 - yy0;
	yp = -yp;
	}
else
	{
	rflg = 0;
	a = aa;
	b = bb;
	y0 = yy0;
	}


if( (aa <= 1.0) || (bb <= 1.0) )
	{
	y = yp * yp / 2.0;
	}
else
	{
	lgm = (yp * yp - 3.0)/6.0;
	x0 = 2.0/( 1.0/(2.0*a-1.0)  +  1.0/(2.0*b-1.0) );
	y = yp * sqrt( x0 + lgm ) / x0
		- ( 1.0/(2.0*b-1.0) - 1.0/(2.0*a-1.0) )
		* (lgm + 5.0/6.0 - 2.0/(3.0*x0));
	y = 2.0 * y;
	if( y < MINLOG )
		{
		x0 = 1.0;
		goto under;
		}
	}

x = a/( a + b * exp(y) );
y = incbet( a, b, x );
yp = (y - y0)/y0;
if( fabs(yp) < 1.0e-1 )
	goto newt;

/* Resort to interval halving if not close enough */
x0 = 0.0;
x1 = 1.0;
di = 0.5;

for( i=0; i<20; i++ )
	{
	if( i != 0 )
		{
		x = di * x1  + (1.0-di) * x0;
		y = incbet( a, b, x );
		yp = (y - y0)/y0;
		if( fabs(yp) < 1.0e-3 )
			goto newt;
		}

	if( y < y0 )
		{
		x0 = x;
		di = 0.5;
		}
	else
		{
		x1 = x;
		di *= di;
		if( di == 0.0 )
			di = 0.5;
		}
	}

if( x0 == 0.0 )
	{
under:
	mtherr( "incbi", UNDERFLOW );
	goto done;
	}

newt:

x0 = x;
lgm = lgam(a+b) - lgam(a) - lgam(b);

for( i=0; i<10; i++ )
	{
/* compute the function at this point */
	if( i != 0 )
		y = incbet(a,b,x0);
/* compute the derivative of the function at this point */
	d = (a - 1.0) * log(x0) + (b - 1.0) * log(1.0-x0) + lgm;
	if( d < MINLOG )
		{
		x0 = 0.0;
		goto under;
		}
	d = exp(d);
/* compute the step to the next approximation of x */
	d = (y - y0)/d;
	x = x0;
	x0 = x0 - d;
	if( x0 <= 0.0 )
		{
		x0 = 0.0;
		goto under;
		}
	if( x0 >= 1.0 )
		{
		x0 = 1.0;
		goto under;
		}
	if( i < 2 )
		continue;
	if( fabs(d/x0) < 256.0 * MACHEP )
		goto done;
	}

done:
if( rflg )
	x0 = 1.0 - x0;
return( x0 );
}
