Modifying the value of a float-like object

Piet van Oostrum piet at cs.uu.nl
Wed Apr 15 11:38:57 CEST 2009


>>>>> Eric.Le.Bigot at spectro.jussieu.fr (ELB) wrote:

[snip]

>ELB> A couple of ideas I had:

>ELB> 1) Define a FloatWithUncert object, but get instance values as x(), as
>ELB> in "x()+y()".  The code is relatively legible.  'x' is mutable.  But
>ELB> formulas don't look so good, and you can't drop a float replacement
>ELB> for 'x', as floats are not callable.

>ELB> 2) Write all expressions that could contain FloatWithUncert objects
>ELB> with a 'float()' wrapper ("float(x)+float(y)"), after defining the
>ELB> FloatWithUncert.__float__() method.  FloatWithUncert would be
>ELB> mutable.  The code is a little bit heavy, but it is explicit.  'x'
>ELB> could be a pure float.

Would this be what you want?

class Float(object):
    def __init__(self, value, uncert=0.0):
        self.value = value
        self.uncert = uncert
        
    def __float__(self):
        return self.value

    def __str__(self):
        return str(self.value)

    def __add__(self, other):
        return self.value + other
    
    __radd__ = __add__

# etc for all other arithmetic and logical operators (but this can be
# automated, see the thread "Automatically generating arithmetic
# operations for a subclass")

>>> x = Float(3.14, 0.01)
>>> print x
3.14
>>> from math import sin
>>> sin(x)
0.0015926529164868282
>>> x.value = -3.14
>>> print x
-3.14
>>> sin(x)
-0.0015926529164868282
>>> x + 1
-2.1400000000000001
>>> y = Float(7.0, 0.3)
>>> print y
7.0
>>> x + y
3.8599999999999999
>>> 

If you write your own functions they might have to coerce your Float
objects to real floats ocassionally by using float(param) instead of
param. 
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list