ohhh myyy gawd c++ issues!!!

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
Rebornxeno
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 85
Joined: Thu Jun 23, 2011 11:12 am

ohhh myyy gawd c++ issues!!!

Post 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?
User avatar
wtetzner
Chaos Rift Regular
Chaos Rift Regular
Posts: 159
Joined: Wed Feb 18, 2009 6:43 pm
Current Project: waterbear, GBA game + editor
Favorite Gaming Platforms: Game Boy Advance
Programming Language of Choice: OCaml
Location: TX
Contact:

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

Post 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.
The novice realizes that the difference between code and data is trivial. The expert realizes that all code is data. And the true master realizes that all data is code.
Rebornxeno
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 85
Joined: Thu Jun 23, 2011 11:12 am

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

Post 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!
Post Reply