Advertisement
Guest User

Int-multiply-using-floats trickery

a guest
Jul 6th, 2011
708
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.56 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. static float fnms(float a, float b, float c)
  5. {
  6.   return (float) -((double) a * (double) b - (double) c);
  7. }
  8.  
  9. int main()
  10. {
  11.   union
  12.   {
  13.     float f;
  14.     unsigned u;
  15.   } u;
  16.  
  17.   const float a = 255.0f;
  18.   const float aScaled = -a * pow(2.0f, 23.0f);
  19.  
  20.   for (int b=0; b < 65536; b++)
  21.   {
  22.     u.u = 0x3f800000 | b;
  23.     float product = fnms(u.f, aScaled, aScaled);
  24.     int prodAsInt = (int) product;
  25.     if (prodAsInt != a*b)
  26.     {
  27.       printf("Mismatch! b=%d\n", b);
  28.       return 1;
  29.     }
  30.   }
  31.  
  32.   return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement