Page 1 of 1

ohhh myyy gawd c++ issues!!!

Posted: Sat Oct 27, 2012 11:08 pm
by Rebornxeno
I have one int array and one float array, both of size 9. I multiply them by each other. I have two ways of doing it that I thought were equal, but give different results!

Code: Select all

for (int a = 0; a < 9; a++)
{
	blue2 += ((pixels[a] &blue) * kernel[a]);
}

blue2 = (((pixels[0] &blue) * kernel[0]) + ((pixels[1] &blue) * kernel[1]) + ((pixels[2] &blue) * kernel[2]) + ((pixels[3] &blue) * kernel[3]) + ((pixels[4] &blue) * kernel[4]) + ((pixels[5] &blue) * kernel[5]) + ((pixels[6] &blue) * kernel[6]) + ((pixels[7] &blue) * kernel[7]) + ((pixels[8] &blue) * kernel[8]));
As you can see, the first one uses a for-loop, and the second one unrolls it all out. When I use the second one, I get the results I expect, and when I use the first one ( the for-loop ) I get weird results and I can't figure out why.

The pixels array is int, and the kernel array is float. Is it just me, or is there something wrong going on?

Re: ohhh myyy gawd c++ issues!!!

Posted: Sun Oct 28, 2012 8:16 am
by wtetzner
What is the type of blue2?

If blue2 is an int, then at each point in the loop, you're rounding your result to an int. In the unrolled version, you are doing floating point arithmetic, before saving the entire result in an int. So with the second version, you only do the rounding once, where in the loop version, you do it for every iteration.

Try using a float as your accumulator in the loop, and then after the loop save the answer into blue2.

Re: ohhh myyy gawd c++ issues!!!

Posted: Sun Oct 28, 2012 7:31 pm
by Rebornxeno
blue2 is type int! I knew it had something to do with the different types, but couldn't figure out what! You hit the nail right on the head dude! I changed blue2 to float and when I needed it, just type-casted it back to int and voila! Thank you kind sir!