tags:

views:

191

answers:

5

I can print a range of numbers easily using range, but is is possible to print a range with 1 decimal place from -10 to 10?

e.g

-10.0, -9.9, -9.8 all they way through to +10?

+7  A: 
[i/10.0 for i in range(-100,101)]

(The .0 is not needed in Python 3.x)

KennyTM
Note that the `.` is very important. In Python 2 without `from __future__ import division`, this is necessary not to be performing floor division.
Mike Graham
Better yet, do ".0," as that makes it much more obvious then a single decimal point :)
Aea
A: 

numpy.arange might serve your purpose well.

Mike Graham
I don't think this is a good idea unless you don't use numpy heavily. If it's just for OP's purpose it might be overdoing.
Dacav
+2  A: 

There's a recipe on ActiveState that implements a floating-point range. In your example, you can use it like

frange(-10, 10.01, 0.1)

Note that this won't generate 1 decimal place on most architectures because of the floating-point representation. If you want to be exact, use the decimal module.

AndiDog
A: 
print(', '.join('%.1f' % x/10.0 for x in range(-100, 101)))

should do exactly what you ask (the printing part, that is!) in any level of Python (a pretty long line of course -- a few hundred characters!-). You could omit the outer parenthese in Python 2, could omit the .0 bit in Python 3, etc, but coding as shown will work across Python releases.

Alex Martelli
A: 

Define a simple function, like:

def frange(fmin, fmax, fleap):
    cur=fmin
    while cur<fmax:
        yield cur
        cur+=fleap

Call it using generators, e.g.:

my_float_range=[i for i in frange(-10,10,.1)]

Some sanity checks (for example, that fmin<fmax) can be added to the function body.

Adam Matan