float precision and caching

Eric Mattes ericmattes at yahoo.com
Mon Feb 3 17:13:56 EST 2003


Hi all. Can anyone suggest the most processor-efficient way to trim the
precision of a floating-point value?

I'm using two strings and a floating-point number as a key into a hash that
I use to cache alpha blending calculations. I discovered (the hard way) that
this produces an out-of-control cache that grows like crazy because the
floating point values vary so much.

I thought a good way to control this would be to convert the float into a
string like this:

alpha = "%.2f" % a

(where 'a' is the original float) and then use that string in the hash key.
Here is my code:

alpha = "%.2f" % a # trim the alpha value so we have a small hash dictionary
blendkey = cPickle.dumps((fc,bc,alpha))
if not self.blendcache.has_key(blendkey):
    ....do the stuff and store the key...
else: return self.blendcache[blendkey]

can anyone think of a better/faster way to do this?
-E






More information about the Python-list mailing list