floating point range generator
imbosol at aerojockey.com
Mon Jul 28 20:05:35 CEST 2003
Bengt Richter wrote:
> On Mon, 28 Jul 2003 02:22:59 GMT, Carl Banks <imbosol at aerojockey.com> wrote:
>>The most robust way to handle this is to iterpolate, i.e., instead of
>>passing start, stop, and step, pass start, stop, and n_intervals:
>> def interiter(start, stop, n_intervals):
>> diff = stop - start
>> for i in xrange(n_intervals+1):
>> yield start + (i*diff)/n_intervals
> To guarantee the exact end points, maybe:
> def interiter(start, stop, n_intervals):
> for i in xrange(n_intervals+1):
> yield ((n_intervals-i)/fn)*start + (i/fn)*stop
> but shouldn't that be xrange(n_intervals) and leave out
> the final point (thus exact but invisible ;-).
Well, I thought about that.
In the interests of practicality beats purity, when you're
interpolating (instead of stepping as in range) you should include the
final endpoint. In my experience, when when you divide a segment into
intervals, you almost always want to include both endpoints.
If you use the Python convention of not including the final point in
the iteration, and someone decides they do want the final endpoint,
then it's kind of a pain to calculate what point you should use to get
the final "endpoint", and you lose accuracy on top of it.
So, my suggestion when iterating over an interval is this: If you pass
in a stepsize, then don't include the final point. If you pass in a
number of intervals, then do include the final point. I think the
practicality of it justifies the different conventions.
More information about the Python-list