mgf.js (2266B)
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 isNonNegativeInteger = require( '@stdlib/math/base/assert/is-nonnegative-integer' ); 24 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 25 var exp = require( '@stdlib/math/base/special/exp' ); 26 var pow = require( '@stdlib/math/base/special/pow' ); 27 var PINF = require( '@stdlib/constants/float64/pinf' ); 28 29 30 // MAIN // 31 32 /** 33 * Evaluates the moment-generating function (MGF) for a binomial distribution with number of trials `n` and success probability `p` at a value `t`. 34 * 35 * @param {number} t - input value 36 * @param {NonNegativeInteger} n - number of trials 37 * @param {Probability} p - success probability 38 * @returns {number} evaluated MGF 39 * 40 * @example 41 * var y = mgf( 0.5, 20, 0.2 ); 42 * // returns ~11.471 43 * 44 * @example 45 * var y = mgf( 5.0, 20, 0.2 ); 46 * // returns ~4.798e29 47 * 48 * @example 49 * var y = mgf( 0.9, 10, 0.4 ); 50 * // returns ~99.338 51 * 52 * @example 53 * var y = mgf( 0.0, 10, 0.4 ); 54 * // returns 1.0 55 * 56 * @example 57 * var y = mgf( NaN, 20, 0.5 ); 58 * // returns NaN 59 * 60 * @example 61 * var y = mgf( 0.0, NaN, 0.5 ); 62 * // returns NaN 63 * 64 * @example 65 * var y = mgf( 0.0, 20, NaN ); 66 * // returns NaN 67 * 68 * @example 69 * var y = mgf( 0.2, 1.5, 0.5 ); 70 * // returns NaN 71 * 72 * @example 73 * var y = mgf( 0.2, -2.0, 0.5 ); 74 * // returns NaN 75 * 76 * @example 77 * var y = mgf( 0.2, 20, -1.0 ); 78 * // returns NaN 79 * 80 * @example 81 * var y = mgf( 0.2, 20, 1.5 ); 82 * // returns NaN 83 */ 84 function mgf( t, n, p ) { 85 var base; 86 if ( 87 isnan( t ) || 88 isnan( n ) || 89 isnan( p ) || 90 p < 0.0 || 91 p > 1.0 || 92 !isNonNegativeInteger( n ) || 93 n === PINF 94 ) { 95 return NaN; 96 } 97 base = 1.0 - p + (p * exp(t)); 98 return pow( base, n ); 99 } 100 101 102 // EXPORTS // 103 104 module.exports = mgf;