'use strict';

// MODULES //

var abs = require( '@stdlib/math/base/special/abs' );


// VARIABLES //

var P = [
{{P}}
];
var Q = [
{{Q}}
];
var END = P.length - 1;


// MAIN //

/**
* Evaluates a rational function (i.e., the ratio of two polynomials described by the coefficients stored in \\(P\\) and \\(Q\\)).
*
* ## Notes
*
* -   Coefficients should be sorted in ascending degree.
* -   The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
* @private
* @param {number} x - value at which to evaluate the rational function
* @returns {number} evaluated rational function
*/
function evalrational( x ) {
	var s1;
	var s2;
	var i;

	if ( x === 0.0 ) {
		return {{ratio}};
	}
	if ( abs( x ) <= 1.0 ) {
		s1 = P[ END ];
		s2 = Q[ END ];
		for ( i = END-1; i >= 0; i-- ) {
			s1 *= x;
			s2 *= x;
			s1 += P[ i ];
			s2 += Q[ i ];
		}
	} else {
		x = 1.0 / x; // use inverse to avoid overflow
		s1 = P[ 0 ];
		s2 = Q[ 0 ];
		for ( i = 1; i <= END; i++ ) {
			s1 *= x;
			s2 *= x;
			s1 += P[ i ];
			s2 += Q[ i ];
		}
	}
	return s1 / s2;
}


// EXPORTS //

module.exports = evalrational;
