0

Hi, I'm trying to loop through vaules less than 1 eg say from 0.1-0.9. I tried the code below and I get the error "ValueError: xrange() arg 3 must not be zero". My question is, is it possible to loop through decimal values.

for x in xrange(0.1,0.9,0.1):
     print x

Thanks in advance for your reply.

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by vegaseat
1

The Python functions xrange() and range() only take integer values. For floating point values you have to roll your own function. I called mine frange() ...

def frange(start=0, stop=0, step=1.0):
    """similar to xrange, but handles floating point numbers"""
    if step <= 0:
        while start > stop:
            yield start
            start += step
    else:
        while start < stop:
            yield start
            start += step

# testing ...
for x in frange(1.5, 4.7):
    print(x)

print("-"*20)

#testing count down ...
for x in frange(11.2, -4, -2.9):
    print(x)

"""
my result -->
1.5
2.5
3.5
4.5
--------------------
11.2
8.3
5.4
2.5
-0.4
-3.3
"""

The module numpy has an arange() function ...

# module numpy (numeric python extensions, high speed)
# free from: http://sourceforge.net/projects/numpy

import numpy as np

for x in np.arange(11.2, -4, -2.9):
    print x

"""
my result -->
11.2
8.3
5.4
2.5
-0.4
-3.3
"""
Votes + Comments
Nice use of generators
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.