this is something that has always bugged me when I look at code around the web and in so much of the literature: why do we multiply by 255 and not 256?
sometimes you'll see something like this:
float input = some_function(); // returns 0.0 to 1.0
byte output = input * 255.0;
(i'm assuming that there's an implicit floor
going on during the type conversion).
am i not correct in thinking that this is clearly wrong?
consider this:
- what range of
input
gives an output of0
? (0 -> 1/255], right? - what range of
input
gives an output of1
? (1/255 -> 2/255], great! - what range of
input
gives an output of255
? only 1.0 does. any significantly smaller value ofinput
will return a loweroutput
.
this means that input
is not evently mapped onto the output range.
ok. so you might think: ok use a better rounding function:
byte output = round(input * 255.0);
where round()
is the usual mathematical rounding to zero decimal places. but this is still wrong. ask the same questions:
- what range of
input
gives an output of0
? (0 -> 0.5/255] - what range of
input
gives an output of1
? (0.5/255 -> 1.5/255], twice as much as for0
! - what range of
input
gives an output of255
? (254.5/255 -> 1.0), again half as much as for1
so in this case the input range isn't evenly mapped either!
IMHO. the right way to do this mapping is this:
byte output = min(255, input * 256.0);
again:
- what range of
input
gives an output of0
? (0 -> 1/256] - what range of
input
gives an output of1
? (1/256 -> 2/256] - what range of
input
gives an output of255
? (255/256 -> 1.0)
all those ranges are the same size and constitute 1/256th of the input.
i guess my question is this: am i right in considering this a bug, and if so, why is this so prevalent in code?
edit: it looks like i need to clarify. i'm not talking about random numbers here or probability. and i'm not talking about colors or hardware at all. i'm talking about converting a float in the range [0,1] evenly to a byte [0,255] so each range in the input that corresponds to each value in the output is the same size.