math-evalpoly
Version:
Evaluates a polynomial.
74 lines (63 loc) • 1.63 kB
JavaScript
/* jshint evil:true */
;
// EVALPOLY FACTORY //
/**
* FUNCTION: factory( c )
* Returns a function for evaluating a polynomial.
*
* @param {Number[]|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} c - polynomial coefficients sorted in ascending degree
* @returns {Function} function for evaluating a polynomial
*/
function factory( c ) {
var f;
var n;
var m;
var i;
// Code generation. Start with the function definition...
f = 'return function evalpoly(x){';
// Create the function body...
n = c.length;
// If no coefficients, the function always returns 0...
if ( n === 0 ) {
f += 'return 0;';
}
// If only one coefficient, the function always returns that coefficient...
else if ( n === 1 ) {
f += 'return ' + c[ 0 ] + ';';
}
// If more than one coefficient, apply Horner's method...
else {
// If `x == 0`, return the first coefficient...
f += 'if(x===0){return ' + c[ 0 ] + ';}';
// Otherwise, evaluate the polynomial...
f += 'return ' + c[ 0 ];
m = n - 1;
for ( i = 1; i < n; i++ ) {
f += '+x*';
if ( i < m ) {
f += '(';
}
f += c[ i ];
}
// Close all the parentheses...
for ( i = 0; i < m-1; i++ ) {
f += ')';
}
f += ';';
}
// Close the function:
f += '}';
// Create the function in the global scope:
return ( new Function( f ) )();
/**
* returns
* function evalpoly( x ) {
* if ( x === 0 ) {
* return c[ 0 ];
* }
* return c[0]+x*(c[1]+x*(c[2]+x*(c[3]+...+x*(c[n-2]+x*c[n-1]))));
* }
*/
} // end FUNCTION factory()
// EXPORTS //
module.exports = factory;