I am implementing a simple dot product algorithm into actionscript 3.0 codes. Here is the basic example.
(1, 2, 3) • (7, 9, 11) = 1×7 + 2×9 + 3×11 = 58
I have a simple code here.
public var array1:Array = [1, 2, 3]; // 4, 10, 18
public var array2:Array = [4, 5, 6];
public var answer:Number = 0;
public function Algorithm()
{
multiply();
}
public function multiply()
{
var temp:Number = 0 ;
while (temp < array1.length)
{
answer = array1[temp] * array2[temp];
temp++;
}
trace(answer += answer);
}
But when I trace it..instead of 32, it goes 36… looks like it is adding 4 again for the last answer.
Its bugging me.
You are overwriting answer each time the array loops. The only value that is being stored is the last (3*6 = 18). In your trace you are effectively doubling that, giving you 36 every time. Try this:
Then just trace answer at the end.