Loop with float increments (frange)?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • forum@anton.e4ward.com

    #1

    Loop with float increments (frange)?

    Hi!

    what's the standard way for a "for" loop with float increments?

    Anton

  • Dan Sommers

    #2
    Re: Loop with float increments (frange)?

    On 14 Apr 2006 06:11:38 -0700,
    forum@anton.e4w ard.com wrote:
    [color=blue]
    > what's the standard way for a "for" loop with float increments?[/color]

    Use a while loop instead:

    f = initial_value
    while f <= final_value:
    process(f)
    f = f + increment

    Note that there is no general guarantee that f will actually be
    final_value; see also <http://docs.python.org/tut/node16.html>.

    Regards,
    Dan

    --
    Dan Sommers
    <http://www.tombstoneze ro.net/dan/>
    "I wish people would die in alphabetical order." -- My wife, the genealogist

    Comment

    • Diez B. Roggisch

      #3
      Re: Loop with float increments (frange)?

      forum@anton.e4w ard.com wrote:
      [color=blue]
      > Hi!
      >
      > what's the standard way for a "for" loop with float increments?[/color]

      AFAIK there is no, but you should be easily able to write an frange
      yourself:


      def frange(from, to, step):
      while from < to:
      yield from
      from += step

      for x in frange(10.5, 23.4, 0.3):
      print x


      Diez

      Comment

      • Tim Peters

        #4
        Re: Loop with float increments (frange)?

        [forum@anton.e4w ard.com][color=blue][color=green]
        >> what's the standard way for a "for" loop with float increments?[/color][/color]

        [Dan Sommers][color=blue]
        > Use a while loop instead:
        >
        > f = initial_value
        > while f <= final_value:
        > process(f)
        > f = f + increment
        >
        > Note that there is no general guarantee that f will actually be
        > final_value; see also <http://docs.python.org/tut/node16.html>.[/color]

        There's no guarantee that the `while` loop will execute "the expected"
        number of times either, and it's generally a Bad Idea to do "f +=
        increment" inside the loop: the value of f suffers an additional
        rounding error on each iteration that way, potentially making it drift
        away from "the expected" value more & more as the loop goes on.

        Standard careful numeric practice is this way:

        n = compute the number of iterations you want to make in total
        for i in xrange(n):
        process(initial _value + i * increment)

        Then each value computed suffers a total of only two rounding errors
        (one for the multiply, one for the add), independent of how large `n`
        may be, and doesn't get worse as the loop goes on.

        Comment

        Working...