473,809 Members | 2,687 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 1743
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
4064
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 my script down so that mysql inserts are occuring every 1/2 second or so.
10
2219
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
1838
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
3970
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
14735
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
1418
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) .... print list(i)
2
4726
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 taken the users answers and inserted them into a
7
6605
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
1634
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 iterator conforming to the STL forward iterator definition. Then, the class would look like: ...
0
9721
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9602
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10639
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10383
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9200
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7661
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5688
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
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
3
3015
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.