Normalize any value in range (-inf…+inf) to (0…1). Is it possible?

前端 未结 3 729
半阙折子戏
半阙折子戏 2021-02-06 14:23

If we have concrete range of max..min value it is quite easy to normalize it to 0..1 float values, but if we don\'t have concrete limits? Is it possible to build universal funct

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-06 14:56

    If you don't mind bit-dibbling and are confident that code uses IEEE binary 64-bit floating point, some fast code with only a few FP math operations

    // If double is 64-bit  and same endian as integer
    double noramlize01(double x) {
      assert(x == x);  // fail if x is NaN
      union {
        double d;
        int64_t i64;
        uint64_t u64;
      } u = {x};
      double d;
      if (u.i64  < 0) {
        u.u64 -= 0x8000000000000000;
        d = (double) -u.i64;
      } else {
        d = (double) u.i64;
      }
      return d/(+2.0 * 0x7ff0000000000000) + 0.5;
    }
    

    // Similar test code as this answer

                -inf  0.0000000000000000
      -1.797693e+308  0.0000000000000000
       -3.141593e+00  0.24973844740430023
       -2.718282e+00  0.24979014633262589
       -1.000000e+00  0.25012212994626282
      -2.225074e-308  0.49975574010747437
      -4.940656e-324  0.50000000000000000
       -0.000000e+00  0.50000000000000000
        0.000000e+00  0.50000000000000000
       4.940656e-324  0.50000000000000000
       2.225074e-308  0.50024425989252563
        1.000000e+00  0.74987787005373718
        2.718282e+00  0.75020985366737414
        3.141593e+00  0.75026155259569971
       1.797693e+308  1.0000000000000000
                 inf  1.0000000000000000
    

提交回复
热议问题