Rev | Line | |
---|
[18] | 1 | """ |
---|
| 2 | Combinatorial function using NumPy |
---|
| 3 | OMN, 2001 |
---|
| 4 | """ |
---|
| 5 | |
---|
[6818] | 6 | import numpy as num |
---|
[18] | 7 | |
---|
| 8 | def factorial(n): |
---|
[6818] | 9 | v = num.arange(n)+1 |
---|
| 10 | return num.multiply.reduce(v) |
---|
[18] | 11 | |
---|
| 12 | def binom (n,k): |
---|
| 13 | """ Compute the binomial coefficient n!/(k! (n-k)!) |
---|
| 14 | """ |
---|
| 15 | |
---|
| 16 | if k > n or n < 0 or k < 0: |
---|
| 17 | raise Exception |
---|
| 18 | elif k==n or n==0 or k==0: |
---|
| 19 | return(1) |
---|
| 20 | else: |
---|
[6818] | 21 | v = num.arange(k) + n-k+1 #[n-k+1, ..., n-1, n] |
---|
| 22 | nom = num.multiply.reduce(v) |
---|
[18] | 23 | denom = factorial(k) |
---|
| 24 | |
---|
| 25 | return nom/denom |
---|
| 26 | |
---|
| 27 | def bitvector(i, n): |
---|
| 28 | """Compute binary representation of positive integer i in a word of size n |
---|
| 29 | """ |
---|
| 30 | |
---|
| 31 | b=[0]*n |
---|
| 32 | k=0 |
---|
| 33 | while i > 0: |
---|
| 34 | d = i%2 |
---|
| 35 | b[k] = d |
---|
| 36 | i = i/2 |
---|
| 37 | k = k+1 |
---|
| 38 | if k > n: break |
---|
| 39 | return b |
---|
| 40 | |
---|
| 41 | |
---|
Note: See
TracBrowser
for help on using the repository browser.