[Tutor] range query

D-Man dsh8290@rit.edu
Fri, 19 Jan 2001 10:51:07 -0500

```On Fri, Jan 19, 2001 at 11:07:50PM +0900, kevin parks wrote:
| how come range only works with integers? Is there a way to do the same thing with floats-value steps? It seems very unPython like to me.
|
| why can't you do this:
| range(3, 0.5)

This isn't how range orders its arguments.  This says you want to
count up from 3 to 0.  Not exactly possible. ex:

range( 0 , 3 )

[ 0 , 1 , 2 ]

Also, range is defined only for integers, so if you do provide a step
(the /third/ argument) it will be converted to an int first

range( 0 , 3 , 0.5 )

**** Error : zero step size

# (Oh, 0.5 was rounded down)

range( 0 , 3 , 1.5 )

[ 0 , 1 , 2 ]

|
| [0.0 ,0.5, 1.0, 1.5, 2.0, 2.5, 3.0]

This could be useful.  Perhaps the following (untested) could work

map( range( 0 , 6 ) , lambda x : x/2.0 ) :

#  My idea here is to double your range, then halve each value.  This
#  ought to work . . .

|
| hmm...
|
| inquiring minds want to know...

My guess is that floats are just bad things.  Basically, ints are
well-behaved while floats aren't.  Floats are usually represented
using binary bits and often in IEEE 754 format.  The IEEE format can't
represent all floating point numbers.  It uses a Scientific Notation
style ( 1.x**n ) to store it.  Floats can therefore only represent
numbers that exist as powers of 2.

In C, C++, etc, you can't write the following (equivalent) :

for( float i = 0 ; i < 3 ; i++ )
{
...
}

because the meaning of incrementing a float by 1 is undefined.  Also,
float comparisons rarely work right ex:

if ( (0.0/3.0) == 0 ) :
print "true"
else :
print "false"

is likely to print "false".

|
| cheers,
| kevin
| Seoul, Korea
|

As someone else suggested, you could use a list comprehension.  You
could also define your own float_range function that behaves the way
you want it to, but be careful with precision issues.

HTH,
-D

```