6

Possible Duplicate:
Python decimal range() step value

I have a cycle in C:

for (float i = 0; i < 2 * CONST; i += 0.01) {
    // ... do something
}

I need the same cycle in python, but:

for x in xxx

not the same.

How can i make it in python?

Community
  • 1
  • 1
MrSil
  • 608
  • 6
  • 12

4 Answers4

5
for i in xrange(200*CONST):
    i = i/100.0
ajon
  • 7,868
  • 11
  • 48
  • 86
5

You are almost on the line. This is how you do it on a list: -

your_list = [1, 2, 3]
for eachItem in your_list:
    print eachItem

If you want to iterate over a certain range: -

for i in xrange(10):
    print i

To give a step value you can use a third parameter, so in your case it would be: -

for i in xrange(2 * CONST, 1):
    print i

But you can only give an integer value as step value.

If you want to use float increment, you would have to modify your range a little bit:-

for i in xrange(200 * CONST):
    print i / 100.0
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
4

Write your own range generator. This helps you deal with non-integer step values with ease, all across your program, solving multiple issues of the same kind. It also is more readable.

def my_range(start, end, step):
    while start <= end:
        yield start
        start += step

for x in my_range(1, 2 * CONST, 0.01):
    #do something

For-loop reference

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
  • 1
    This looks the most correct; both `range` and `xrange` work on integers and a custom range-like generator allows to work around that. See also http://stackoverflow.com/questions/477486/python-decimal-range-step-value – Kos Oct 27 '12 at 09:05
  • 1
    Adding lots of floats together is a recipe for inaccuracy. Following link shows a better way to create a float range: http://code.activestate.com/recipes/66472/ – Dunes Oct 27 '12 at 09:10
  • Yes, that way's nice, and it's easy to turn that function into a generator too. – Kos Oct 27 '12 at 09:55
3

numpy has a method that can be used to create a range of floats.

from numpy import arange

for x in arange(0, 2*CONST, 0.01):
    do_something(x)
Dunes
  • 37,291
  • 7
  • 81
  • 97