[Tutor] range() fractional increment

spir denis.spir at free.fr
Tue Mar 31 10:51:30 CEST 2009


Le Mon, 30 Mar 2009 20:44:28 -0700 (PDT),
james carnell <jimcarnell at yahoo.com> s'exprima ainsi:

> 1) I feel dumb for asking this.
> 2) I looked for 20 minutes and didn't find an answer
> 
> Trying to make a drawLine function in a 2d array.
> 
> example:
> x0000   row = 25 : col = 10
> x0000   row = 26 : col = 10.3
> x0000   row = 27 : col = 10.6
> 0x000   row = 28 : col = 11
> 0x000   row = 29 : col = 11.3
> 0x000   row = 30 : col = 11.6
> 00x00   row = 31 : col = 12
> 
> for row in range(25,31,1):
>     for col in range(10,12, 0.3):  #<- Crash Bang doesn't work 0.3 = zero =
> infinite loop?
> 
> so then I tried...
> 
> >>> c = 10
> >>> while(c < 12.3):
> ...     print c
> ...     c += 1.0/3.0
> ...
> 10
> 10.3333333333
> 10.6666666667
> 11.0
> 11.3333333333
> 11.6666666667
> 12.0
> 
> is there no way to do it with a range function (and have it still look like
> you're not on crack)?

Had a tool func for this, and a generator version:

def fractRange(start,end,step):
	diff = end - start
	step_nr = int(diff/step) + 1
	return [start + (step*i) for i in range(step_nr)]
def fractRangeGen(start,end,step):
	diff = end - start
	step_nr = int(diff/step) + 1
	for i in range(step_nr):
		yield start + (step*i)
print fractRange(-1,1.1,1.0/3)
for x in fractRangeGen(-1,1.1,1.0/3):
	print x,
==>
[-1.0, -0.66666666666666674, -0.33333333333333337, 0.0, 0.33333333333333326, 0.66666666666666652, 1.0]
-1.0 -0.666666666667 -0.333333333333 0.0 0.333333333333 0.666666666667 1.0

denis
------
la vita e estrany


More information about the Tutor mailing list