Modifying the value of a float-like object

Dave Angel davea at ieee.org
Tue Apr 14 14:45:47 EDT 2009


Eric.Le.Bigot at spectro.jussieu.fr wrote:
> It looks like what is needed here are a kind of "mutable float".  Is
> there a simple way of creating such a type?  I don't mind changing the
> value through x.value =.23 instead of x = 1.23... :)
>
> On Apr 14, 3:03 pm, Eric.Le.Bi... 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 =.14) so that any expression like "x
>> +y" uses the new value.
>>
>> I thought of two solutions, both of which I can't make to work:
>>
>> 1) Use a class that inherits from float.  This takes care of the
>> "behave like float" part.  But is it possible to change the value of
>> the float associated with an instance?  That is, is it possible to
>> do:  "x =yFloat(1.23); x.change_value(3.14)" so that x's float value
>> becomes 3.14?
>>
>> 2) The other possibility I thought of was: use a class that defines a
>> 'value' member (x.value).  This takes care of the "value can be
>> changed" part.  But is it possible/easy to make it fully behave like a
>> float (including when passed to functions like math.sin)?
>>
>> Alternatively, I'd be happy with a way of handling numerical
>> uncertainties in Python calculations (such as in "calculate the value
>> and uncertainty of a*sin(b) knowing that a=0 +/- 0.1 and b=1.00 +/-
>> 0.01").
>>
>> Any idea would be much appreciated!
>>     

The answer to your original question is no.  If the value can be changed, then it doesn't behave like a float.  And that's not just a pedantic answer, it's a serious consideration.

You have to decide what characteristics of a float you need to mimic, and which ones you don't care about, and which ones you want to change.  Only after having a pretty good handle on those answers can you pick a "best" implementation.

Let's call this new type a nfloat, and let's assume you have a function that returns one.  That might be a constructor, but it may not, so we're keeping our options open.
  myval = newfunction(42.0)



What do you want to happen when you execute   b = myval ?   Presumably 
you want them to be "equal" but in what sense?  Suppose you then change 
one of them with your suggested attribute/method.
     myval.value = newfunction("aaa")

is b the same as it was (like a float would be), or is b also changed?

Do you need lots of functions to work on one of these nfloats, or could 
you use them as follows:
     sin( b.value )

Instead of using .value to change the underlying float, how about if you 
use [0] ?  Just use a list of size 1.





More information about the Python-list mailing list