[Tutor] range()-like function for dealing with floats...?

Andreas Kostyrka andreas at kostyrka.org
Fri Mar 30 19:28:51 CEST 2007


* Carroll, Barry <Barry.Carroll at psc.com> [070330 19:15]:
> Try entering "python range float" at your personal favorite search
> engine.  I tried it on Google.  Here is the first entry returned:
> 
> 	ASPN : Python Cookbook : frange(), a range function with float
> ...
> 	Sadly missing in the Python standard library, this function
> allows 
> 	to use ranges, just as the built-in function range(), but with 
> 	float arguments. ...
> 	aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66472 
> 	- 32k - Cached - Similar pages 
> 
> There were lots of others.

Just don't forget that floats are not evenly spaced. The hole between
possible floats gets bigger the more you move away from zero.

On my IA32 Linux laptop I get:

>>> (1e+16) + 1 == (1e+16)
True
>>> (1e+16) + 10 == (1e+16)
False

So a frange(1e+16, (1e+16) + 1000, 1) won't work, or at best will
result something else than what you thought it would.

That's probably the reason why frange is not part of the standard
library: It's not possible to define it sensible for all float ranges,
and floats have many properties that make them fiendish. Typically,
programming courses just ignore the problematic aspects (at best one
learns that floats should not be used to represent money), one usually
has to take a course on Numerics to get the details.

Andreas


More information about the Tutor mailing list