Quick average of 2 numbers

Started by
22 comments, last by Unfadable 18 years, 5 months ago
Does anyone know of any slick tricks to calculate the average of 2 numbers w/o using addition? Its okay if the number is off by 1. Just looking for fast technique. I thought of using look-up tables, but couldn't come up with a way to index into it quickly. I'm thinking theres a bit trick. Thanks
Advertisement
Umm, why do want to speed up addition? Adding two numbers together and dividing by two should be extremely quick (you could use a bit shift for the division if you really want to).

There's probably a good reason; I'm just a little confused... [looksaround]
You could use a look-up table, but that would probably be slower than adding them and dividing by 2.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
I don't know of any speed tricks, but one useful formula is (a & b) + (a ^ b) / 2 to avoid integral overflow from addition.
I guess I should've posted this in general.

I'm trying to speed up my image blending operation and am willing to sacrifice (some quality) to do it. The addition, shift trick is quite fast enough for the amount of blending I'm doing.
Consider that shifting isn't necessarily faster than multiplication or division on modern processors (division is still slow, however). Your compiler may even decide to replace your shift operator with anything it considers better.

See the topic discussed here:
Is shift still worth it?

The bottom line is, let the compiler do the optimization and write your code in such a way it can do it well.
Hey,

This sounds like a time I'd consider using SSE instructions. Either that or do it on the GPU or something. The more parallel processing you can get, the better IMO here, and you're unlikely to get better than the GPU.

--CJM
I guess you could speed it up a little by replacing the division with a multiplication... x * 0.5f

*shrugs*
Quote:Original post by Wavarian
I guess you could speed it up a little by replacing the division with a multiplication... x * 0.5f

*shrugs*

I doubt this would end up being faster than the bit-shift option suggested since it would require a conversion to float, then back to int for the RGB value.
Quote:Original post by Wavarian
I guess you could speed it up a little by replacing the division with a multiplication... x * 0.5f

This ranks right up there with the shift "optimization." It is something that the compiler can do if such a change is worth it.

*edit: And I doubt anything will be worth it. Go back a step, and see if there's some way to blend multiple pixels at once. Chances are, that's your best bet, short of using somebody else's library.

CM

This topic is closed to new replies.

Advertisement