Generalized range

Beliavsky beliavsky at aol.com
Fri Apr 27 08:39:56 EDT 2007


On Apr 27, 1:32 am, a... at mac.com (Alex Martelli) wrote:
> Michael Hoffman <cam.ac... at mh391.invalid> wrote:
> > tkp... 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).

You may be referring to the Fortran DO loop with a REAL loop variable,
for example

do x=1.5,3.5,0.5
   print*,x
end do

This was part of standard Fortran 77, so one should blame the
standards committee, not the compiler writers. Very few features of
F77 were deleted in Fortran 95, but this was one of them. In practice,
nothing gets deleted from commercial Fortran compilers.

At the SciPy site http://www.scipy.org/Cookbook/OptimizationAndFitDemo1
there is some code

   1 from enthought.chaco.wx import plt
   2 from scipy import arange, optimize, special
   3
   4 plt.figure()
   5 plt.hold()
   6 w = []
   7 z = []
   8 x = arange(0,10,.01)
   9
  10 for k in arange(1,5,.5):
  11    y = special.jv(k,x)
  12    plt.plot(x,y)
  13    f = lambda x: -special.jv(k,x)
  14    x_max = optimize.fminbound(f,0,6)
  15    w.append(x_max)
  16    z.append(special.jv(k,x_max))
  17
  18 plt.plot(w,z, 'ro')
  19 from scipy import interpolate
  20 t = interpolate.splrep(w, z, k=3)
  21 s_fit3 = interpolate.splev(x,t)
  22 plt.plot(x,s_fit3, 'g-')
  23 t5 = interpolate.splrep(w, z, k=5)
  24 s_fit5 = interpolate.splev(x,t5)
  25 plt.plot(x,s_fit5, 'y-')

I think the use of arange with a non-integer increment is poor style,
for reasons discussed in this thread.




More information about the Python-list mailing list