time-to-botec

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

factory.js (2101B)


      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 // MODULES //
     22 
     23 var constantFunction = require( '@stdlib/utils/constant-function' );
     24 var isnan = require( '@stdlib/math/base/assert/is-nan' );
     25 var exp = require( '@stdlib/math/base/special/exp' );
     26 var pow = require( '@stdlib/math/base/special/pow' );
     27 
     28 
     29 // MAIN //
     30 
     31 /**
     32 * Returns a function for evaluating the moment-generating function (MGF) for a triangular distribution with lower limit `a`, upper limit `b`, and mode `c`.
     33 *
     34 * @param {number} a - lower limit
     35 * @param {number} b - upper limit
     36 * @param {number} c - mode
     37 * @returns {Function} MGF
     38 *
     39 * @example
     40 * var mgf = factory( 0.0, 2.0, 1.0 );
     41 * var y = mgf( -1.0 );
     42 * // returns ~0.3996
     43 *
     44 * y = mgf( 2.0 );
     45 * // returns ~10.205
     46 */
     47 function factory( a, b, c ) {
     48 	var bmc;
     49 	var bma;
     50 	var cma;
     51 
     52 	if (
     53 		isnan( a ) ||
     54 		isnan( b ) ||
     55 		isnan( c ) ||
     56 		a > c ||
     57 		c > b
     58 	) {
     59 		return constantFunction( NaN );
     60 	}
     61 	bmc = b - c;
     62 	bma = b - a;
     63 	cma = c - a;
     64 	return mgf;
     65 
     66 	/**
     67 	* Evaluates the moment-generating function (MGF) for a triangular distribution.
     68 	*
     69 	* @private
     70 	* @param {number} t - input value
     71 	* @returns {number} evaluated MGF
     72 	*
     73 	* @example
     74 	* var y = mgf( 0.5 );
     75 	* // returns <number>
     76 	*/
     77 	function mgf( t ) {
     78 		var ret;
     79 
     80 		if ( isnan( t ) ) {
     81 			return NaN;
     82 		}
     83 		if ( t === 0.0 ) {
     84 			return 1.0;
     85 		}
     86 		ret = (bmc * exp( a * t )) - (bma * exp( c * t ));
     87 		ret += cma * exp( b * t );
     88 		ret *= 2.0;
     89 		ret /= bma * cma * bmc * pow( t, 2.0 );
     90 		return ret;
     91 	}
     92 }
     93 
     94 
     95 // EXPORTS //
     96 
     97 module.exports = factory;