time-to-botec

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

factory.js (2031B)


      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 expm1 = require( '@stdlib/math/base/special/expm1' );
     26 var log1p = require( '@stdlib/math/base/special/log1p' );
     27 var LNHALF = require( '@stdlib/constants/float64/ln-half' );
     28 
     29 
     30 // MAIN //
     31 
     32 /**
     33 * Returns a function for evaluating the logarithm of the cumulative distribution function (CDF) for a Laplace distribution with location parameter `mu` and scale parameter `b`.
     34 *
     35 * @param {number} mu - location parameter
     36 * @param {PositiveNumber} b - scale parameter
     37 * @returns {Function} logCDF
     38 *
     39 * @example
     40 * var logcdf = factory( 3.0, 1.5 );
     41 *
     42 * var y = logcdf( 1.0 );
     43 * // returns ~-2.026
     44 *
     45 * y = logcdf( 4.0 );
     46 * // returns ~-0.297
     47 */
     48 function factory( mu, b ) {
     49 	if ( isnan( mu ) || isnan( b ) || b <= 0.0 ) {
     50 		return constantFunction( NaN );
     51 	}
     52 	return logcdf;
     53 
     54 	/**
     55 	* Evaluates the logarithm of the cumulative distribution function (CDF) for a Laplace distribution.
     56 	*
     57 	* @private
     58 	* @param {number} x - input value
     59 	* @returns {number} evaluated logCDF
     60 	*
     61 	* @example
     62 	* var y = logcdf( 2.0 );
     63 	* // returns <number>
     64 	*/
     65 	function logcdf( x ) {
     66 		var z;
     67 		if ( isnan( x ) ) {
     68 			return NaN;
     69 		}
     70 		z = ( x - mu ) / b;
     71 		if ( x < mu ) {
     72 			return LNHALF + z;
     73 		}
     74 		return LNHALF + log1p( -expm1( -z ) );
     75 	}
     76 }
     77 
     78 
     79 // EXPORTS //
     80 
     81 module.exports = factory;