473,578 Members | 3,102 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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**********@PA Myahoo.com

Jul 18 '05 #1
6 1731
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*******@yaho o.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.or g> 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 incompatibiliti es, 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
4047
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 cent. Even if i remove the mysql insert query and just loop through the file , it still hits 100 per cent CPU. This has the knock on effect of slowing...
10
2201
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(*) where I want to receive tuples of (item1, item2, item3) from the iterables. But it doesn't work well for a situation like: zip(*tuple_iter)
3
1830
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++) SomeFunction(*pr);
24
3935
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 = s2 = s3 = for value in ???(s1, s2, s3):
13
14717
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
1391
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 was using a lot of iterators and I forgot that that specific function parameter was one. Exemple : >>> def f(i): .... print list(i) .... ...
2
4710
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 question. I have a web survey that I am working on and have successfully dynamically taken the info from a database, displayed it on the screen and then...
7
6587
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
1616
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 arithmetic operations on objects I don't know. In C++, the method doing that was a template, and all that was required is that the template class has an...
0
7778
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8290
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7874
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6522
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5664
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3798
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2292
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1389
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1113
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.