473,412 Members | 2,239 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,412 software developers and data experts.

Looping using iterators with fractional values

Hello,

Making the transition from Perl to Python, and have a
question about constructing a loop that uses an iterator
of type float. How does one do this in Python?

In Perl this construct quite easy:

for (my $i=0.25; $i<=2.25; $i+=0.25) {
printf "%9.2f\n", $i;
}

Thanks in advance for your help.
Daran Rife
da**********@PAMyahoo.com

Jul 18 '05 #1
6 1717
drife wrote:
Hello,

Making the transition from Perl to Python, and have a
question about constructing a loop that uses an iterator
of type float. How does one do this in Python?

Use a generator:
def iterfloat(start, stop, inc): .... f = start
.... while f <= stop:
.... yield f
.... f += inc
.... for x in iterfloat(0.25, 2.25, 0.25): .... print '%9.2f' % x
....
0.25
0.50
0.75
1.00
1.25
1.50
1.75
2.00
2.25


Jul 18 '05 #2
drife wrote:
Hello,

Making the transition from Perl to Python, and have a
question about constructing a loop that uses an iterator
of type float. How does one do this in Python?

In Perl this construct quite easy:

for (my $i=0.25; $i<=2.25; $i+=0.25) {
printf "%9.2f\n", $i;
}


<=Py2.3:

for i in [x/4.0 for x in xrange(1, 10)]:
print "%9.2f" % i

Py2.4:

for i in (x/4.0 for x in xrange(1, 20)):
print "%9.2f" % i

Reinhold
Jul 18 '05 #3
Mark McEahern wrote:
drife wrote:
Hello,

Making the transition from Perl to Python, and have a
question about constructing a loop that uses an iterator
of type float. How does one do this in Python?

Use a generator:
>>> def iterfloat(start, stop, inc): ... f = start
... while f <= stop:
... yield f
... f += inc
... >>> for x in iterfloat(0.25, 2.25, 0.25): ... print '%9.2f' % x
...
0.25
0.50
0.75
1.00
1.25
1.50
1.75
2.00
2.25 >>>


Or use the numarray module:

py> import numarray as na
py> for f in na.arange(0.25, 2.25, 0.25):
.... print '%9.2f' % f
....
0.25
0.50
0.75
1.00
1.25
1.50
1.75
2.00

Steve
Jul 18 '05 #4
"drife" <da*******@yahoo.com> writes:
Hello,

Making the transition from Perl to Python, and have a
question about constructing a loop that uses an iterator
of type float. How does one do this in Python?

In Perl this construct quite easy:

for (my $i=0.25; $i<=2.25; $i+=0.25) {
printf "%9.2f\n", $i;
}

Generally, you don't loop incrementing floating point values, as
you're liable to be be surprised. This case will work as you expect
because .25 can be represented exactly, but that's not always the
case.

Python loops are designed to iterate over things, not as syntactic
sugar for while. So you can either do the while loop directly:

i = 0.25
while i <= 2.25:
print "%9.2f" % i
i += 0.25

Or - and much safer when dealing with floating point numbers - iterate
over integers and generate your float values:

for j in range(1, 9):
i = j * .25
print "%9.2f" % i

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 18 '05 #5
Mike Meyer wrote:
Or - and much safer when dealing with floating point numbers - iterate
over integers and generate your float values:

for j in range(1, 9):
i = j * .25
print "%9.2f" % i


There's a glitch there, though - should be range(1, 10).

Reinhold

PS: I'm wondering whether my genexp approach or this one is preferable.
Readability is equal, I would say, but how about speed?

Brought up a few timeits:

Python 2.3
----------

for i in [x/4.0 for x in range(1, 10)]: 36,9 sec

for j in range(1, 10): i = j * 0.25: 33,7 sec

Python 2.4
----------

for i in (x/4.0 for x in range(1, 10)): 32,5 sec

for j in range(1, 10): i = j * 0.25: 28,4 sec
So what does that tell us?
(a) don't use genexps where there is a simpler approach
(b) Py2.4 rocks!

Reinhold
Jul 18 '05 #6
Mike Meyer wrote:
Or - and much safer when dealing with floating point numbers - iterate
over integers and generate your float values: for j in range(1, 9):
i = j * .25
print "%9.2f" % i


I agree with this suggestion. As an historical aside, Fortran had loops
with floating point variables for decades, but in 1995, the first
standard in a while to REMOVE features, this was one of the few things
deleted. The Fortran standards committee is very conservative about
creating backwards incompatibilities, but they must have thought loops
with floating point variables are so error-prone -- and alternatives
with integer counters are so easy to write -- that they put their foot
down. I know the OP is asking about Python, but the principle is the
same.

Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: kaptain kernel | last post by:
i've got a while loop thats iterating through a text file and pumping the contents into a database. the file is quite large (over 150mb). the looping causes my CPU load to race up to 100 per...
10
by: Steven Bethard | last post by:
So, as I understand it, in Python 3000, zip will basically be replaced with izip, meaning that instead of returning a list, it will return an iterator. This is great for situations like: zip(*)...
3
by: cppaddict | last post by:
Hi, I need to a way to loop thru vectors (or some other appropriate collection type) using constructs such as: for (pr = someVector.begin(); pr != someVector.end(); pr++) ...
24
by: Lasse Vågsæther Karlsen | last post by:
I need to merge several sources of values into one stream of values. All of the sources are sorted already and I need to retrieve the values from them all in sorted order. In other words: s1 = ...
13
by: Joseph Garvin | last post by:
When I first came to Python I did a lot of C style loops like this: for i in range(len(myarray)): print myarray Obviously the more pythonic way is: for i in my array: print i
21
by: Christophe | last post by:
Is there a good reason why when you try to take an element from an already exausted iterator, it throws StopIteration instead of some other exception ? I've lost quite some times already because I...
2
by: clinttoris | last post by:
Hello, If someone could help me it would be appreciated as I am not having much luck. I'm struggling with my asp code and have some questions relating to asp and oracle database. First...
7
by: linq936 | last post by:
Hi, The following is a psudo code to describe my question: vector<int> ints; vector<int>::iterator itr; while (itr != ints.end()){ int j = some_function(*i); if (j>0){ ints.push_back(j); }
10
by: Pierre Thibault | last post by:
Hello! I am currently trying to port a C++ code to python, and I think I am stuck because of the very different behavior of STL iterators vs python iterators. What I need to do is a simple...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.