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?
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?
[i/10.0 for i in range(-100,101)]
(The .0
is not needed in Python 3.x)
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.
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.
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.