Modifying the value of a float-like object

Piet van Oostrum piet at
Wed Apr 15 11:38:57 CEST 2009

>>>>> Eric.Le.Bigot at (ELB) wrote:


>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
>>> from math import sin
>>> sin(x)
>>> x.value = -3.14
>>> print x
>>> sin(x)
>>> x + 1
>>> y = Float(7.0, 0.3)
>>> print y
>>> x + y

If you write your own functions they might have to coerce your Float
objects to real floats ocassionally by using float(param) instead of
Piet van Oostrum <piet at>
URL: [PGP 8DAE142BE17999C4]
Private email: piet at

More information about the Python-list mailing list