John Carmack在Quake III源代码中有一个特殊的功能,它计算浮点的平方根,比常规的快4倍(float)(1.0/sqrt(x)),包括一个奇怪的0x5f3759df常量.请参阅下面的代码.有人可以逐行解释这里究竟发生了什么以及为什么这比常规实现快得多?
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y;
i = 0x5f3759df - ( i >> 1 );
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) );
#ifndef Q3_VM
#ifdef __linux__
assert( !isnan(y) );
#endif
#endif …Run Code Online (Sandbox Code Playgroud) 为什么以下代码的输出:"我是:1075838976"?
#include <stdio.h>
int main(){
int i = 2;
float num = 2.5;
i = *((int *)& num);
printf("i is: %d\n", i);
}
Run Code Online (Sandbox Code Playgroud)
不等于:
#include <stdio.h>
int main(){
int i = 2;
float num = 2.5;
i = num;
printf("i is: %d\n", i);
}
Run Code Online (Sandbox Code Playgroud)
哪个输出:"我是2"?谢谢.