'use strict';

// TODO: implementation

/**
* Computes the principal square root.
*
* @param {number} x - input value
* @returns {number} principal square root
*
* @example
* var v = sqrt( 4.0 );
* // returns 2.0
* @example
* var v = sqrt( 9.0 );
* // returns 3.0
* @example
* var v = sqrt( 0.0 );
* // returns 0.0
* @example
* var v = sqrt( -4.0 );
* // returns NaN
* @example
* var v = sqrt( NaN );
* // returns NaN
*/
var sqrt = Math.sqrt;


// EXPORTS //

module.exports = sqrt;

'use strict';

// MODULES //

var getHighWord = require( '@stdlib/math/base/utils/float64-get-high-word' );
var fromWords = require( '@stdlib/math/base/utils/float64-from-words' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );


// CONSTANTS //

var T2 = [
	0x1500, 0x2ef8, 0x4d67, 0x6b02, 0x87be, 0xa395, 0xbe7a, 0xd866,
	0xf14a, 0x1091b,0x11fcd,0x13552,0x14999,0x15c98,0x16e34,0x17e5f,
	0x18d03,0x19a01,0x1a545,0x1ae8a,0x1b5c4,0x1bb01,0x1bfde,0x1c28d,
	0x1c2de,0x1c0db,0x1ba73,0x1b11c,0x1a4b5,0x1953d,0x18266,0x16be0,
	0x1683e,0x179d8,0x18a4d,0x19992,0x1a789,0x1b445,0x1bf61,0x1c989,
	0x1d16d,0x1d77b,0x1dddf,0x1e2ad,0x1e5bf,0x1e6e8,0x1e654,0x1e3cd,
	0x1df2a,0x1d635,0x1cb16,0x1be2c,0x1ae4e,0x19bde,0x1868e,0x16e2e,
	0x1527f,0x1334a,0x11051,0xe951, 0xbe01, 0x8e0d, 0x5924, 0x1edd
];
var BIAS = 9.313225746154785e-10; // 2^-30


// SQRT //

/**
* Computes the principal square root.
*
*
* #### Method
*
* * Initial approximation:
*   Using bit operations, we obtain a 7.8-bit approximation \\( y \\) of \\( \tfrac{1}{\sqrt(x)} \\).
*
* * Iterative Refinement
*   We apply reciproot iterations to y and multiply the
*   result by \\( x \\) to get an approximation z that matches \\( \sqrt(x) \\)
*   to about 1 ulp. To be exact, we will have
*
*   ``` tex
*   -1\text{ulp} < \sqrt(x) - z < 1.0625\text{ulp}.
*   ```
*
* #### Reference:
*
* * Ren Li. 1992. Reciproot Algorithm -- Correctly Rounded?.
*   Technical Report. University of California at Berkeley, Berkeley, CA, USA.
*
*
* @param {number} x - input value
* @returns {number} principal square root
*
* @example
* var v = sqrt( 4.0 );
* // returns 2.0
* @example
* var v = sqrt( 9.0 );
* // returns 3.0
* @example
* var v = sqrt( 0.0 );
* // returns 0.0
* @example
* var v = sqrt( -4.0 );
* // returns NaN
* @example
* var v = sqrt( NaN );
* // returns NaN
*/
function sqrt( x ) {
	var x0;
	var y0;
	var k;
	var y;
	var z;
	if ( x === 0.0 || isnan( x ) || x === PINF ) {
		return x;
	}
	if ( x < 0.0 ) {
		return NaN;
	}
	x0 = getHighWord( x );

	k = 0x5fe80000 - (x0>>1);
	y0 = k - T2[63&(k>>14)];

	y = fromWords( y0, 0 );

	// Perform reciproot iterations...
	y = y * ( 1.5 - 0.5*x*y*y );
	y = y * ( (1.5-BIAS) - 0.5*x*y*y );

	z = x * y;
	z = z + 0.5*z*(1-z*y);

	return z;
} // end FUNCTION sqrt()


// EXPORTS //

module.exports = sqrt;

Use reciproot algorithm to calculate principal square root