jabo
jabo

Reputation: 11

How to print a range with decimal points in Python?

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?

Upvotes: 1

Views: 1771

Answers (5)

Adam Matan
Adam Matan

Reputation: 136141

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.

Upvotes: 0

Alex Martelli
Alex Martelli

Reputation: 881555

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.

Upvotes: 0

AndiDog
AndiDog

Reputation: 70128

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.

Upvotes: 2

kennytm
kennytm

Reputation: 523214

[i/10.0 for i in range(-100,101)]

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

Upvotes: 7

Mike Graham
Mike Graham

Reputation: 76683

numpy.arange might serve your purpose well.

Upvotes: 0

Related Questions