float precision and caching

Peter Hansen peter at engcorp.com
Mon Feb 3 17:23:44 EST 2003


Eric Mattes wrote:
> 
> 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]

Are you by any chance merging the two strings together with a string
representation of the floating point value, just to get a string which
you use as the key in the dictionary?

If so, you should know you can use a tuple as a key, in which case you
can keep the two strings separate, and avoid converting the float to
its string representation.  Use the round() method Alex mentioned and
put them together like (string1, string2, roundedfloatval) and you 
should be all set.

-Peter




More information about the Python-list mailing list