3

I stumbled across this Wikipedia article about fast inverse square root calculations, and there were a few lines that interested me in the example code.

y  = number;
i  = * ( long * ) &y;
i  = 0x5f3759df - ( i >> 1 );
y  = * ( float * ) &i;

This is written in C and makes sense in that context, but is there a way to achieve the same effect in Java without true pointers?

1 Answers1

0

You can use a ByteBuffer for example (or Unsafe if you must)

ByteBuffer bb = ByteBuffer.allocate(4);
// y = number
// i  = * ( long * ) &y; // assuming long is 32-bit, not long long
bb.putFloat(0, number);
int i = bb.getInt(0);
// i  = 0x5f3759df - ( i >> 1 );
i  = 0x5f3759df - ( i >> 1 ); 
// y  = * ( float * ) &i;
bb.putInt(0, i);
float y = bb.getFloat(0);

Instead of using ByteBuffer or memory tricks you can do

// y  = number;
float y = number;
// i  = * ( long * ) &y;
int i = Float.floatToRawIntBits(f);
// i  = 0x5f3759df - ( i >> 1 );
i  = 0x5f3759df - ( i >> 1 ); 
// y  = * ( float * ) &i;
y = Float.intBitsToFloat(i);
Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075