File: factorial.py

package info (click to toggle)
python-visual 1%3A5.12-1.6
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 7,708 kB
  • ctags: 7,635
  • sloc: cpp: 15,593; sh: 9,615; ansic: 6,631; python: 4,737; makefile: 384
file content (31 lines) | stat: -rw-r--r-- 856 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# factorial and combin functions needed in statistical computations
# Bruce Sherwood, Carnegie Mellon University, 2000

def factorial(x):
    if x <= 0.:
        if x == 0.: return 1.
        else: raise 'Cannot take factorial of negative number'
    fact = 1.
    nn = 2.
    while nn <= x:
        fact = fact*nn
        nn = nn+1.
    if nn <> x+1: raise 'Argument of factorial must be an integer'
    return fact

def combin(x, y):
    # combin(x,y) = factorial(x)/[factorial(y)*factorial(x-y)]
    z = x-y
    num = 1.0
    if y > z:
        y,z = z,y
    nn = int(z+1.)
    while nn <= x:
        num = num*nn
        nn = nn+1.
    if nn <> x+1: raise 'Illegal arguments for combin function'
    return num/factorial(y)

if __name__ == '__main__':
    print 'factorial(6) = 6! =', factorial(6)
    print 'combin(6,2) = 6!/(2!(6-2)!) =', combin(6,2)