pdf.js (2322B)
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 exp = require( '@stdlib/math/base/special/exp' ); 24 var pow = require( '@stdlib/math/base/special/pow' ); 25 var sqrt = require( '@stdlib/math/base/special/sqrt' ); 26 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 27 var normal = require( './../../../../../base/dists/normal/cdf' ).factory; 28 var PI = require( '@stdlib/constants/float64/pi' ); 29 30 31 // VARIABLES // 32 33 var normalCDF = normal( 0.0, 1.0 ); 34 35 36 // MAIN // 37 38 /** 39 * Evaluates the probability density function (PDF) for a truncated normal distribution with endpoints `a` and `b`, location parameter `mu` and scale parameter `sigma` at a value `x`. 40 * 41 * @param {number} x - input value 42 * @param {number} a - minimum support 43 * @param {number} b - maximum support 44 * @param {number} mu - location parameter 45 * @param {PositiveNumber} sigma - scale parameter 46 * @returns {number} evaluated PDF 47 * 48 * @example 49 * var y = pdf( 0.9, 0.0, 1.0, 0.0, 1.0 ); 50 * // returns ~0.7795 51 * 52 * @example 53 * var y = pdf( 0.9, 0.0, 1.0, 0.5, 1.0 ); 54 * // returns ~0.9617 55 * 56 * @example 57 * var y = pdf( 0.9, -1.0, 1.0, 0.5, 1.0 ); 58 * // returns ~0.5896 59 * 60 * @example 61 * var y = pdf( 1.4, 0.0, 1.0, 0.0, 1.0 ); 62 * // returns 0.0 63 * 64 * @example 65 * var y = pdf( -0.9, 0.0, 1.0, 0.0, 1.0 ); 66 * // returns 0.0 67 */ 68 function pdf( x, a, b, mu, sigma ) { 69 var s2x2; 70 var A; 71 var B; 72 var C; 73 74 if ( 75 isnan( x ) || 76 isnan( a ) || 77 isnan( b ) || 78 sigma <= 0.0 || 79 a >= b 80 ) { 81 return NaN; 82 } 83 if ( x < a || x > b ) { 84 return 0.0; 85 } 86 s2x2 = 2.0 * pow( sigma, 2.0 ); 87 A = 1.0 / ( sqrt( s2x2 * PI ) ); 88 B = -1.0 / ( s2x2 ); 89 C = normalCDF( (b-mu)/sigma ) - normalCDF( (a-mu)/sigma ); 90 return A * exp( B * pow( x - mu, 2.0 ) ) / C; 91 } 92 93 94 // EXPORTS // 95 96 module.exports = pdf;