Generalized range

Alex Martelli aleax at mac.com
Fri Apr 27 01:32:51 EDT 2007


Michael Hoffman <cam.ac.uk at mh391.invalid> wrote:

> tkpmep at hotmail.com wrote:
> > Thanks - you have covered a fair bit of gorund here - I will modify
> > myRange taking your suggestions into account. The one suggestion that
> > I'm going to have to think through is repeatedly incrementing res.
> > 
> > I deliberately did not use this as repeated addition can cause
> > rounding errors to accumulate, making the loop run a little longer or
> > shorter than necessary. I thought I would be far less likely to run
> > into rounding issues with a multiplicative construct - hence my use of
> > epsilon, and my question about an appropriate value for it
> 
> You are right about rounding issues--with a sufficiently small step, the
> way I have done it, it could become an infinite loop. But you can still
> do it with multiplication, without using an epsilon constant. How about
> something like this:
> 
> index = 0
> while res < maximum:
>      yield minimum + (step * index)
>      index += 1

Absolutely (with your later correction of actually assigning res), MUCH
better than the misguided attempts based on repeatedly adding 'step'.

I've taught "numerical computing" in university, and I would have had to
fail anybody who'd misunderstood floating-point computations badly
enough to try that "+=step" idea (including, sigh, the coders of several
Fortran compilers who were popular at that time).

These days, I _heartily_ recommend "Real Computing Made Real" by Foreman
Acton -- the best programming book without one line of code in any
language (it's all formulas and graphs).  Anybody who has trouble
following it must understand they should NOT use floating point numbers
until they've gotten the prereqs (which aren't all that deep:
engineering-undergrad-level algebra and calculus, plus
<http://docs.sun.com/source/806-3568/ncg_goldberg.html> and a couple
weeks' worth of refresher courses on fundamental algorithms such as
Newton's root-finding approach and the like -- I shudder to think how
many people with CS bachelor degrees and even post-grad degrees are just
never taught these fundamentals, yet end up having to program _some_
floating point computations, mistakenly thinking they can...).


Alex
 



More information about the Python-list mailing list