time-to-botec

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

factory.js (2069B)


      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 degenerate = require( './../../../../../base/dists/degenerate/pdf' ).factory;
     25 var isnan = require( '@stdlib/math/base/assert/is-nan' );
     26 var exp = require( '@stdlib/math/base/special/exp' );
     27 var pow = require( '@stdlib/math/base/special/pow' );
     28 var PINF = require( '@stdlib/constants/float64/pinf' );
     29 
     30 
     31 // MAIN //
     32 
     33 /**
     34 * Returns a function for evaluating the probability density function (PDF) for a Rayleigh distribution with scale parameter `sigma`.
     35 *
     36 * @param {NonNegativeNumber} sigma - scale parameter
     37 * @returns {Function} PDF
     38 *
     39 * @example
     40 * var pdf = factory( 0.5 );
     41 * var y = pdf( 1.0 );
     42 * // returns ~0.541
     43 *
     44 * y = pdf( 0.1 );
     45 * // returns ~0.392
     46 */
     47 function factory( sigma ) {
     48 	var s2i;
     49 	var s2;
     50 	if ( isnan( sigma ) || sigma < 0.0 ) {
     51 		return constantFunction( NaN );
     52 	}
     53 	if ( sigma === 0.0 ) {
     54 		return degenerate( 0.0 );
     55 	}
     56 	s2 = pow( sigma, 2.0 );
     57 	s2i = 1.0 / s2;
     58 	return pdf;
     59 
     60 	/**
     61 	* Evaluates the probability density function (PDF) for a Rayleigh distribution.
     62 	*
     63 	* @private
     64 	* @param {number} x - input value
     65 	* @returns {number} evaluated PDF
     66 	*
     67 	* @example
     68 	* var y = pdf( 2.3 );
     69 	* // returns <number>
     70 	*/
     71 	function pdf( x ) {
     72 		if ( isnan( x ) ) {
     73 			return NaN;
     74 		}
     75 		if ( x < 0.0 || x === PINF ) {
     76 			return 0.0;
     77 		}
     78 		return s2i * x * exp( -pow( x, 2.0 ) / ( 2.0 * s2 ) );
     79 	}
     80 }
     81 
     82 
     83 // EXPORTS //
     84 
     85 module.exports = factory;