dhiltonp

hexbright dot_product

Dec 29th, 2012
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. int hexbright::dot_product(int* vector1, int* vector2) {
  2.   // the max value sum could hit is technically > 2^16.
  3.   //  However, the only instance where this is possible is if both vectors have
  4.   //  experienced maximum acceleration on all axes - with 4 of the 6 being the max in the negative
  5.   //  direction (-32 min, 31 max), (31*100/21.3) = 145, (-32*100/21.3) = -150
  6.   //  3*(150^2) = 67500 (not safe)
  7.   //  (150*150)+(150*150)+(145*145) = 66025 (not safe)
  8.   //  (150*150)+(150*145)+(145*145) = 65275 (safe)
  9.   //  3*(145^2) = 63075 (safe)
  10.   // Given the difficulty of triggering this condition, I'm using an int.
  11.   //  This could also be avoided by /100 inside the loop, costing 12 bytes.
  12.   //  We should revisit this decision when drop detect code has been written.
  13.   // An alternate solution would be to convert the sensor using READING*100/21.622,
  14.   //  giving a max of 147.  3*(147^2) = 64827 (safe).  A max of 148 would be
  15.   //  safe so long as no more than 5 values are -32.
  16.   //  This would alter 1G to be 98 instead of 100, the closest values being 97(21) or 101(22).
  17.   unsigned int sum = 0; // max value is about 3*(150^2), a tad over the maximum unsigned int
  18.   for(int i=0;i<3;i++) {
  19.     //sum+=vector1[i]*vector2[i]/100; // avoids overflow, but costs space
  20.     sum+=vector1[i]*vector2[i];
  21.   }
  22.   return sum/100; // small danger of overflow
  23. }
Advertisement
Add Comment
Please, Sign In to add comment