Modifying the value of a float-like object

Eric.Le.Bigot at spectro.jussieu.fr Eric.Le.Bigot at spectro.jussieu.fr
Wed Apr 15 15:26:48 CEST 2009


Thanks, Piet!  Before reading your post, I did not know that defining
__float__() was enough for math.sin() to be able to calculate
something!

To summarize my current understanding for the original problem:

- Mutable floats seem to be the only way of performing (correct)
uncertainty calculations without modifying the code of the modules in
which the calculations are done (in particular when we call object
methods that perform calculations whose parameters are _not passed as
arguments by the caller_ [Peter's post shows a simpler, less general
case]).

- A mutable float can be obtained through a numpy.ndarray object (see
Dan's post), which can be subclassed so as to add an "uncertainty"
attribute.  Pros: the way the mutable float behaves in calculation is
taken care of by numpy.  Cons: this requires numpy.

- A mutable float can also be created directly (see Piet's post), and
the regular float behavior can be quite well (or fully?) approximated
by defining a __float__() member, as well as implementing the basic
methods of Python's floats (addition, etc.).  Pros: this is clean
Python.  Cons: as Piet noted, one might have to explicitly use float
(x) in some expressions.

I'd like to add (in particular for those who think that mutable floats
are dangerous beasts to play with) that the example "x = y" given in
previous posts (where "y" is a number with uncertainty) actually gives
the intended behavior when calculating "x-y" with its uncertainty,
which would not be the case if "y" was copied by value into "x".  When
it comes to calculating uncertainties, this example shows that
mutability is actually a good thing.

Well, that's two implementations to be tried!  I'll get back to this
thread with the results!  Thanks for the lively thread!

On Apr 15, 1:41 pm, Piet van Oostrum <p... at cs.uu.nl> wrote:
> In my solution I think you can mostly use normal formula's with the
> Float objects, although there may be some functions that give problems
> for example if they have explicit tests like type(x) == float. Why don't
> you give it a try?
> --
> Piet van Oostrum <p... at cs.uu.nl>
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p... at vanoostrum.org




More information about the Python-list mailing list