fastmath library?

William Annis annis at biostat.wisc.edu
Thu Nov 16 16:18:33 EST 2000


"Pete Shinners" <pete at visionart.com> writes:

> one that uses high-speed lookup tables and estimates for
> low quality results? i'd mainly like one that can handle
> things like square-root, cosine, etc, etc

        This lookup-don't-compute behavior is sometimes called
memoizing.  

> i figure there's got to be something like this already
> available for python?

        Well I've written the little memoizing class below.  I'm not
sure the overhead will help you in the case of sine and cosines, but
certainly will for more complex functions:

----------------------------------------------------------------------
#!/s/bin/python -- # -*- python -*-
# $Id: memoize.py,v 1.1 1999-10-26 09:58:29-05 annis Exp annis $
# $Source: /u/annis/code/python/lib/RCS/memoize.py,v $

"""Create memoizing versions of functions.
"""

class memoize:
    def __init__(self, fn):
        self.fn = fn
        self.args = {}

    def __call__(self, *args):
        if not self.args.has_key(args):
            self.args[args] = apply(self.fn, args)

        return self.args[args]


if __name__ == '__main__':
    import math

    msin = memoize(math.sin)
    print msin(0), msin(math.pi/2), msin(math.pi/4)

----------------------------------------------------------------------

        Basically, it keeps a dictionary of arguments.  When it has
seen the arguments before, it just looks up the data.  When they're
new, it does the computation.  So, this is only helpful when you're
calling the memoized function a lot.

-- 
William Annis - System Administrator - Biomedical Computing Group
annis at biostat.wisc.edu                       PGP ID:1024/FBF64031
Mi parolas Esperanton - La Internacian Lingvon  www.esperanto.org



More information about the Python-list mailing list