From: Zooko O'Whielacronx zooko@zooko.com Date: Sat, 14 Apr 2007 17:54:43 +0000 (+0530) Subject: pyfec: import a copy of mathutil.py from the pyutil library X-Git-Url: https://git.rkrishnan.org/uri/module-simplejson.encoder.html?a=commitdiff_plain;h=28e60f04edf87dbe66f78042cbc41e237488f2c5;p=tahoe-lafs%2Fzfec.git pyfec: import a copy of mathutil.py from the pyutil library darcs-hash:cee8657901117d8dd821c69a274715655ee062fd --- diff --git a/pyfec/fec/util/mathutil.py b/pyfec/fec/util/mathutil.py new file mode 100644 index 0000000..de95a6a --- /dev/null +++ b/pyfec/fec/util/mathutil.py @@ -0,0 +1,92 @@ +# Copyright (c) 2005-2007 Bryce "Zooko" Wilcox-O'Hearn +# mailto:zooko@zooko.com +# http://zooko.com/repos/pyutil +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this work to deal in this work without restriction (including the rights +# to use, modify, distribute, sublicense, and/or sell copies). + +""" +A few commonly needed functions. +""" + +import math + +def div_ceil(n, d): + """ + The smallest integer k such that k*d >= n. + """ + return (n/d) + (n%d != 0) + +def next_multiple(n, k): + """ + The smallest multiple of k which is >= n. + """ + return div_ceil(n, k) * k + +def pad_size(n, k): + """ + The smallest number that has to be added to n so that n is a multiple of k. + """ + if n%k: + return k - n%k + else: + return 0 + +def is_power_of_k(n, k): + return k**int(math.log(n, k) + 0.5) == n + +def next_power_of_k(n, k): + p = 1 + while p < n: + p *= k + return p + +def ave(l): + return sum(l) / len(l) + +def log_ceil(n, b): + """ + The smallest integer k such that b^k >= n. + + log_ceil(n, 2) is the number of bits needed to store any of n values, e.g. + the number of bits needed to store any of 128 possible values is 7. + """ + p = 1 + k = 0 + while p < n: + p *= b + k += 1 + return k + +def linear_fit_slope(ps): + """ + @param ps a sequence of tuples of (x, y) + """ + avex = ave([x for (x, y) in ps]) + avey = ave([y for (x, y) in ps]) + sxy = sum([ (x - avex) * (y - avey) for (x, y) in ps ]) + sxx = sum([ (x - avex) ** 2 for (x, y) in ps ]) + if sxx == 0: + return None + return sxy / sxx + +def permute(l): + """ + Return all possible permutations of l. + + @type l: sequence + @rtype a set of sequences + """ + if len(l) == 1: + return [l,] + + res = [] + for i in range(len(l)): + l2 = list(l[:]) + x = l2.pop(i) + for l3 in permute(l2): + l3.append(x) + res.append(l3) + + return res + diff --git a/pyfec/setup.py b/pyfec/setup.py index 24ba55c..3081ef6 100755 --- a/pyfec/setup.py +++ b/pyfec/setup.py @@ -63,7 +63,7 @@ setup(name='pyfec', url='http://zooko.com/repos/pyfec', license='GNU GPL', platform='Any', - packages=['fec', 'fec.test'], + packages=['fec', 'fec.util', 'fec.test'], classifiers=trove_classifiers, ext_modules=[Extension('_fec', ['fec/fec.c', 'fec/_fecmodule.c',], extra_link_args=extra_link_args, extra_compile_args=extra_compile_args, undef_macros=undef_macros),], )