Velocity Reviews > Loop with float increments (frange)?

# Loop with float increments (frange)?

forum@anton.e4ward.com
Guest
Posts: n/a

 04-14-2006
Hi!

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

Anton

Dan Sommers
Guest
Posts: n/a

 04-14-2006
On 14 Apr 2006 06:11:38 -0700,
http://www.velocityreviews.com/forums/(E-Mail Removed)4ward.com wrote:

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

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

Note that there is no general guarantee that f will actually be

Regards,
Dan

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

Diez B. Roggisch
Guest
Posts: n/a

 04-14-2006
(E-Mail Removed)4ward.com wrote:

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

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

Tim Peters
Guest
Posts: n/a

 04-14-2006
[(E-Mail Removed)4ward.com]
>> what's the standard way for a "for" loop with float increments?

[Dan Sommers]
> 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

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.

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post Isaac Won Python 9 03-04-2013 10:08 AM Carsten Fuchs C++ 45 10-08-2009 09:47 AM anonymousnerd@gmail.com Python 10 06-25-2005 11:06 PM Nicolla MacPherson C++ 4 08-13-2003 09:02 AM bd C Programming 0 07-07-2003 12:09 AM