Reputation: 3
When I try to create an incremental list from a
to b
( so something like [1,1.1,1.2,1.3,...,2] (a=1, b=2), then I start having a problem with the specific code I came up with:
def Range(a,b,r):
lst1=[]
y=a
while y<b:
lst1.append(round(float(y+10**-r),r))
y+=10**-r
return lst1
print Range(1,2,3)
Here, r
is the power of my increments (10**-r)
. For r=1
or r=2
the code works fine and ends at [...,2.0]. But for r=3
or r=4
it ends at [...,2.001] and [...,2.0001] respectively. But then, for r=5
and r=6
it goes back to ending at 2. Is there something wrong with my code or is this some sort of bug?
Upvotes: 0
Views: 667
Reputation: 31260
say, to get a element of 2.001, the lost has to take in y=2.000
That's not true; it's possible that y becomes, say, 1.99999999999997.
You check on y < b
, but then add round(float(y+10**-r),r)
to the list. It's of course possible that the first is true, but the second is still larger than b.
To see what's happening, remove the rounding, and look at the next-to-last number in your lists in the cases where it's going "wrong".
Upvotes: 2