time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

evalpoly.js (1456B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2018 The Stdlib Authors.
      5 *
      6 * Licensed under the Apache License, Version 2.0 (the "License");
      7 * you may not use this file except in compliance with the License.
      8 * You may obtain a copy of the License at
      9 *
     10 *    http://www.apache.org/licenses/LICENSE-2.0
     11 *
     12 * Unless required by applicable law or agreed to in writing, software
     13 * distributed under the License is distributed on an "AS IS" BASIS,
     14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     15 * See the License for the specific language governing permissions and
     16 * limitations under the License.
     17 */
     18 
     19 'use strict';
     20 
     21 // MAIN //
     22 
     23 /**
     24 * Evaluates a polynomial.
     25 *
     26 * ## Notes
     27 *
     28 * -   The implementation uses [Horner's rule][horners-method] for efficient computation.
     29 *
     30 * [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
     31 *
     32 *
     33 * @param {NumericArray} c - polynomial coefficients sorted in ascending degree
     34 * @param {number} x - value at which to evaluate the polynomial
     35 * @returns {number} evaluated polynomial
     36 *
     37 * @example
     38 * var v = evalpoly( [3.0,2.0,1.0], 10.0 ); // 3*10^0 + 2*10^1 + 1*10^2
     39 * // returns 123.0
     40 */
     41 function evalpoly( c, x ) {
     42 	var p;
     43 	var i;
     44 
     45 	i = c.length;
     46 	if ( i < 2 || x === 0.0 ) {
     47 		if ( i === 0 ) {
     48 			return 0.0;
     49 		}
     50 		return c[ 0 ];
     51 	}
     52 	i -= 1;
     53 	p = ( c[ i ] * x ) + c[ i-1 ];
     54 	i -= 2;
     55 	while ( i >= 0 ) {
     56 		p = ( p * x ) + c[ i ];
     57 		i -= 1;
     58 	}
     59 	return p;
     60 }
     61 
     62 
     63 // EXPORTS //
     64 
     65 module.exports = evalpoly;