Advertisement
Guest User

comparison of floats using int representation

a guest
Apr 29th, 2014
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int magic_lt(int a, int b) {
  5.     if ((a < 0) && (b < 0)) {
  6.         return b < a;
  7.     } else {
  8.         return a < b;
  9.     }
  10. }
  11.  
  12. #define HUGE 100000.0
  13. #define TINY 0.0001
  14.  
  15. #define ITERS 1000000
  16. int main() {
  17.     int i;
  18.     float a, b;
  19.     for (i = 0; i < ITERS; i++) {
  20.         a = (drand48() - 0.5) * HUGE;
  21.  
  22.         // три варианта, для сомневающихся
  23.         b = (drand48() - 0.5) * HUGE; // очень разный порядок
  24.         //b = a + (drand48() - 0.5) * TINY; // один порядок
  25.         //b = -a + (drand48() - 0.5) * TINY; // один порядок, разный знак
  26.  
  27.         int aint = *(int*)&a;
  28.         int bint = *(int*)&b;
  29.         if (magic_lt(aint, bint) != (a < b)) {
  30.             printf("wrong!\n");
  31.             printf("%0.9f <-> %d\n", a, aint);
  32.             printf("%0.9f <-> %d\n", b, bint);
  33.         }
  34.     }
  35.     return 0;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement