Binomial Random Variables | function to calculate nCr i . e . , number of ways to choose r out of n objects ; Since nCr is same as nC ( n - r ) To decrease number of iterations ; function to calculate binomial r . v . probability ; driver program
function nCr ( n , r ) { if ( r > n / 2 ) r = n - r ; let answer = 1 ; for ( let i = 1 ; i <= r ; i ++ ) { answer *= ( n - r + i ) ; answer /= i ; } return answer ; } function binomialProbability ( n , k , p ) { return nCr ( n , k ) * Math . pow ( p , k ) * Math . pow ( 1 - p , n - k ) ; } let n = 10 ; let k = 5 ; let p = 1.0 / 3 ; let probability = binomialProbability ( n , k , p ) ; document . write ( " " + k ) ; document . write ( " " + n ) ; document . write ( " " + p ) ; document . write ( " " + probability ) ;