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

nicky van foreest vanforeest@gmail....
Wed Dec 9 15:09:12 CST 2009

Sorry, perhaps I was less clear than I thought. A new attempt... I
want to store floats as keys in a dict. but this is not a smart idea.
To show the problem:

In [1]: a  = {}

In [6]: import math

In [9]: a[1/3.]  = 4

In [10]: a[1./(math.sqrt(3)*math.sqrt(3))]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)

/home/nicky/<ipython console> in <module>()

KeyError: 0.33333333333333337

What would be a smart way to use floats as keys in a dict, in such a
way that the above problem does not occur?

Nicky

2009/12/9 Charles R Harris <charlesr.harris@gmail.com>:
>
>
> On Wed, Dec 9, 2009 at 1:24 PM, nicky van foreest <vanforeest@gmail.com>
> wrote:
>>
>> 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.
>>
>
> This sounds like a proposed solution to a problem. What is the actual
> problem that this is supposed to solve?
>
> Chuck
>
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
>