纯属是膜拜卡马克大神写出的那段代码,当然你有更好的办法可以一起讨论
用python实现《雷神之锤III》中使用的平方根倒数速算法
你好! 第一次写希望大家喜欢,要补充在评论区的热烈欢迎。
关于那段代码好奇的朋友可以直接点击传送门。
原文代码(c)
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threeHalfs = 1.5f;
x2 = number * 0.5f;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // What the fuck?
y = * ( float * ) &i;
y = y * ( threeHalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threeHalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
我的实现方式(python)
import struct
def Q_rsqrt(number):
threehalfs = 1.5
x2 = number * 0.5
y = number
packed_y = struct.pack('f', y)
i = struct.unpack('i', packed_y)[0] # evil floating point bit level hacking
i = 0x5f3759df - (i >> 1) # what the fuck?
packed_i = struct.pack('i', i)
y = struct.unpack('f', packed_i)[0]
y = y * (threehalfs - (x2 * y * y)) #1st iteration
return y
if __name__ == "__main__":
num = 2
result = Q_rsqrt(num)
print(result)
最简单的实现方式(python)
import math
num=2
print(1/math.sqrt(num))
补充
Python中的struct库用于将数据打包成一个固定字节长度的字符串,或从二进制字符串中解压缩数据。它与C语言中的结构体非常相似。使用struct库可以方便地进行网络传输、文件读写等操作。
struct库中包含两个函数:pack和unpack。pack函数将Python数据类型的变量打包成二进制字符串,unpack函数从二进制字符串中解析出Python数据类型的变量。
下面是一个使用struct库打包和解包二进制数据的例子:
import struct
# 打包数据
data = struct.pack('3s i f', b'abc', 123, 3.14)
# 解包数据
s, n, f = struct.unpack('3s i f', data)
print(s) # b'abc'
print(n) # 123
print(f) # 3.14