[reportlab-users] HexColor()

Lalo Martins reportlab-users@reportlab.com
Fri, 14 Feb 2003 14:17:35 -0200


On Fri, Feb 14, 2003 at 09:53:16AM +0200, Marius Gedminas wrote:
> On Thu, Feb 13, 2003 at 07:02:24PM -0200, Lalo Martins wrote:
> > One additional feature my customer wanted is that it allows any "width" for
> > each color, so "f90" and "f09000" and "f00900000" are equivalent.
> 
> Shouldn't that be F90 == ff9900 == ffff99990000?  Both W3C and X11 agree
> on this convention.

I thought so initially, but these aren't numerically equivalent:

>>> from __future__ import division
>>> 0x90 / 0x100
0.5625
>>> 0x99 / 0x100
0.59765625
>>> 0x9 / 0x10
0.5625
>>> 0x900 / 0x1000
0.5625
>>> 0x999 / 0x1000
0.599853515625

Or a simpler proof: 0x8 is half of 0x10, and 0x80 is half of 0x100, while
0x88 is slightly more than half.

As Guido would say, numeric equivalence is IMO the "path of least surprise".


Then again perhaps the whole maths of this have to be rethought - I just
copied the "foo / 0x100" algorithm from the current function, but now I see
it's impossible to get white from it.  Perhaps it should be done so that
'0xf' is white, which means dividing by float(int('f'*w, 16)) - this is more
correct, with the problem that it would make all existing code generate a
slightly different color.

>>> 0x90 / 0xff
0.56470588235294117
>>> 0x99 / 0xff
0.59999999999999998
>>> 0x9 / 0xf
0.59999999999999998
>>> 0x900 / 0xfff
0.56263736263736264
>>> 0x999 / 0xfff
0.59999999999999998

This explains a lot.  Hmm.  Thanks :-)


(Yet a third algorithm would be "(foo + 1) / 0x100", but then you can't get
zero; I tested it and it skews results too much.)

[]s,
                                               |alo
                                               +----
--
            Those who trade freedom for security
               lose both and deserve neither.
--
http://www.laranja.org/                mailto:lalo@laranja.org
         pgp key: http://www.laranja.org/pessoal/pgp

Eu jogo RPG! (I play RPG)         http://www.eujogorpg.com.br/
GNU: never give up freedom                 http://www.gnu.org/