off by 1 error?

david jensen dmj.ccc at gmail.com
Fri Apr 9 22:10:29 CEST 2010


Hi all,

I'm trying to assign a color to various values between some arbitrary
maximum and minimum, and i'd like to go from red to blue to green .
Currently, I have the following, where i'm passing the minimum and
maximum as a 2-tuple:

def getcolor( minmax, curr ):
	rangesize = (minmax[1] - minmax[0]) - 1
	currsize = float( curr - minmax[0] )
	currpos = currsize / rangesize
	colornum = int( currpos*511 + 0.5 )
	r = max( 255 - colornum, 0 )
	g = max( -256 + colornum, 0 )
	b = 255 - ( r+g )
	return r,g,b

1) is there a better way to do this?
2) at the extreme points, this doesn't work: the number of (255, 0,
0)s and (0, 255, 0)s are 1/2 what they should be, and (0, 0, 255) is
double what it should be.

the above algorithm at least doesn't give me things like (0, -1, 256),
which i struggled with for a while, but where is/are my off-by-one(s)?

many thanks

d



More information about the Python-list mailing list