Modifying the value of a float-like object

Dan Goodman dg.gmane at thesamovar.net
Wed Apr 15 04:44:07 EDT 2009


Eric.Le.Bigot at spectro.jussieu.fr wrote:
> Hello,
> 
> Is there a way to easily build an object that behaves exactly like a
> float, but whose value can be changed?  The goal is to maintain a list
> [x, y,…] of these float-like objects, and to modify their value on the
> fly (with something like x.value = 3.14) so that any expression like "x
> +y" uses the new value.

Hi Eric,

Numpy's array object can do something like what you want:

In [27]: x=array(0.0)

In [28]: print x, sin(x)
0.0 0.0

In [29]: x.itemset(pi/2)

In [30]: print x, sin(x)
1.57079632679 1.0

Not sure if this a recommended way of using array or not, but it seems 
to work. The problem is that any calculation you do with such an object 
will result in a float, and not another numpy array (although inplace 
operations work):

In [40]: print (x*2).__class__
<type 'numpy.float64'>

In [41]: x *= 2

In [42]: print x.__class__
<type 'numpy.ndarray'>

So it's not a perfect solution, but it might be OK for what you need.

Dan




More information about the Python-list mailing list