[SciPy-User] maping a float to a function value

nicky van foreest vanforeest at gmail.com
Wed Dec 9 15:24:20 EST 2009


Hi,

I assume that the problem below has been resolved in a clever,
pythonic, way, but I don't know how...

For numerical purposes I want to map floats to other floats, and store
the results. (In math's language, I want to store the mapping x \right
f(x), for x  in the reals). One natural way would be to use a dict.
However, using floats as keys in not particularly smart as the real
numbers (the things I want to deal with) do not map uniquely to
floats. One way to resolve this is to overload the dict object to a
class, like so:

class Function(dict):
    def __init__(self):
        dict.__init__(self)
    def __getitem__(self, x):
        x = round(100*x)
        return dict.__getitem__(self,x)
    def __setitem__(self,x, value):
        x = round(100*x)
        dict.__setitem__(self,x,value)

However, using a class like this has obvious drawbacks, for instance,
now I have to memorize that the internal precision is up to 0.01 (and
I tend to forget stuff like this within a week or so). Of course, I
can take 1e-13 or so as the internal precision, but I still don't like
this approach; I have the feeling that much smarter/more robust ways
exist to resolve this problem.

Thanks

bye

Nicky



More information about the SciPy-User mailing list