factory.js (2105B)
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 26 27 // MAIN // 28 29 /** 30 * Returns a function for evaluating the probability density function (PDF) for a triangular distribution with lower limit `a` and upper limit `b` and mode `c`. 31 * 32 * @param {number} a - lower limit 33 * @param {number} b - upper limit 34 * @param {number} c - mode 35 * @returns {Function} PDF 36 * 37 * @example 38 * var pdf = factory( 0.0, 10.0, 5.0 ); 39 * var y = pdf( 2.0 ); 40 * // returns 0.08 41 * 42 * y = pdf( 12.0 ); 43 * // returns 0.0 44 */ 45 function factory( a, b, c ) { 46 var denom1; 47 var denom2; 48 var denom3; 49 50 if ( 51 isnan( a ) || 52 isnan( b ) || 53 isnan( c ) || 54 a > c || 55 c > b 56 ) { 57 return constantFunction( NaN ); 58 } 59 60 denom1 = ( b - a ) * ( c - a ); 61 denom2 = b - a; 62 denom3 = ( b - a ) * ( b - c ); 63 return pdf; 64 65 /** 66 * Evaluates the probability density function (PDF) for a triangular distribution. 67 * 68 * @private 69 * @param {number} x - input value 70 * @returns {number} evaluated PDF 71 * 72 * @example 73 * var y = pdf( 12.0 ); 74 * // returns <number> 75 */ 76 function pdf( x ) { 77 if ( isnan( x ) ) { 78 return NaN; 79 } 80 if ( x < a ) { 81 return 0.0; 82 } 83 // Case: x >= a 84 if ( x < c ) { 85 return 2.0 * ( x - a ) / denom1; 86 } 87 if ( x === c ) { 88 return 2.0 / denom2; 89 } 90 // Case: x > c 91 if ( x <= b ) { 92 return 2.0 * ( b - x ) / denom3; 93 } 94 // Case: x > b 95 return 0.0; 96 } 97 } 98 99 100 // EXPORTS // 101 102 module.exports = factory;