factory.js (2103B)
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 gamma = require( '@stdlib/math/base/special/gamma' ); 27 var exp = require( '@stdlib/math/base/special/exp' ); 28 var pow = require( '@stdlib/math/base/special/pow' ); 29 30 31 // MAIN // 32 33 /** 34 * Returns a function for evaluating the probability density function (PDF) for a chi distribution with degrees of freedom `k`. 35 * 36 * @param {NonNegativeNumber} k - degrees of freedom 37 * @returns {Function} PDF 38 * 39 * @example 40 * var pdf = factory( 0.5 ); 41 * 42 * var y = pdf( 2.0 ); 43 * // returns ~0.04 44 * 45 * y = pdf( 1.0 ); 46 * // returns ~0.281 47 */ 48 function factory( k ) { 49 var km1; 50 var kh; 51 52 if ( isnan( k ) || k < 0.0 ) { 53 return constantFunction( NaN ); 54 } 55 if ( k === 0.0 ) { 56 return degenerate( 0.0 ); 57 } 58 59 kh = k / 2.0; 60 km1 = k - 1.0; 61 return pdf; 62 63 /** 64 * Evaluates the probability density function (PDF) for a chi distribution with degrees of freedom `k`. 65 * 66 * @private 67 * @param {number} x - input value 68 * @returns {number} evaluated PDF 69 * 70 * @example 71 * var y = pdf( 1.0 ); 72 * // returns <number> 73 */ 74 function pdf( x ) { 75 var out; 76 if ( isnan( x ) ) { 77 return NaN; 78 } 79 if ( x < 0.0 ) { 80 return 0.0; 81 } 82 out = pow( 2.0, 1.0-kh ) * pow( x, km1 ) * exp( -(x*x)/2.0 ); 83 out /= gamma( kh ); 84 return out; 85 } 86 } 87 88 89 // EXPORTS // 90 91 module.exports = factory;