factory.js (1853B)
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 isProbability = require( '@stdlib/math/base/assert/is-probability' ); 25 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 26 var exp = require( '@stdlib/math/base/special/exp' ); 27 var ln = require( '@stdlib/math/base/special/ln' ); 28 29 30 // MAIN // 31 32 /** 33 * Returns a function for evaluating the moment-generating function (MGF) of a geometric distribution with success probability `p`. 34 * 35 * @param {Probability} p - success probability 36 * @returns {Function} MGF 37 * 38 * @example 39 * var mgf = factory( 0.8 ); 40 * var y = mgf( -0.2 ); 41 * // returns ~0.783 42 */ 43 function factory( p ) { 44 if ( !isProbability( p ) ) { 45 return constantFunction( NaN ); 46 } 47 return mgf; 48 49 /** 50 * Evaluates the moment-generating function (MGF) for a geometric distribution. 51 * 52 * @private 53 * @param {number} t - input value 54 * @returns {number} evaluated MGF 55 * 56 * @example 57 * var y = mgf( 0.5 ); 58 * // returns <number> 59 */ 60 function mgf( t ) { 61 var et; 62 var q; 63 if ( isnan( t ) ) { 64 return NaN; 65 } 66 q = 1.0 - p; 67 if ( t >= -ln( q ) ) { 68 return NaN; 69 } 70 et = exp( t ); 71 return ( p * et ) / ( 1.0 - (q * et )); 72 } 73 } 74 75 76 // EXPORTS // 77 78 module.exports = factory;