Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- float InvSqrt (float x)
- {
- float xhalf = 0.5f*x;
- int i = *(int*)&x;
- i = 0x5f3759df - (i>>1);
- x = *(float*)&i;
- x = x*(1.5f - xhalf*x*x);
- return x;
- }
- Input: 79.67
- BitConverter Method: 00:00:01.2809018 (0.1120187)
- Union Method: 00:00:00.6838758 (0.1120187)
- Unsafe Method: 00:00:00.3376401 (0.1120187)
- Math.Pow(x, -0.5): 00:00:01.7133228 (0.112034710535584)
- 1 / Math.Sqrt(x): 00:00:00.3757084 (0.1120347)
- [StructLayout(LayoutKind.Explicit, Size=4)]
- private struct IntFloat {
- [FieldOffset(0)]
- public float floatValue;
- [FieldOffset(0)]
- public int intValue;
- // redundant assignment to avoid any complaints about uninitialized members
- IntFloat(int x) {
- floatValue = 0;
- intValue = x;
- }
- IntFloat(float x) {
- intValue = 0;
- floatValue = x;
- }
- public static explicit operator float (IntFloat x) {
- return x.floatValue;
- }
- public static explicit operator int (IntFloat x) {
- return x.intValue;
- }
- public static explicit operator IntFloat (int i) {
- return new IntFloat(i);
- }
- public static explicit operator IntFloat (float f) {
- return new IntFloat(f);
- }
- }
- float InvSqrt(float x)
- {
- float xhalf = 0.5f * x;
- int i = BitConverter.ToInt32(BitConverter.GetBytes(x), 0);
- i = 0x5f3759df - (i >> 1);
- x = BitConverter.ToSingle(BitConverter.GetBytes(i), 0);
- x = x * (1.5f - xhalf * x * x);
- return x;
- }
- unsafe float InvSqrt(float x) { ... }
Add Comment
Please, Sign In to add comment