【发布时间】:2017-12-22 19:56:09
【问题描述】:
我看到了下面的代码here。
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 heck?
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;
}
下面这行我不明白。
i = * ( long * ) &y;
一般情况下,* 和& 都与指针一起使用,但这里都与变量一起使用。那么,它在这里做什么呢?
【问题讨论】:
-
将浮点数转换为长整数的疯狂方法?
-
这不是快速平方根算法。是的。
-
float x2, y;... i = * ( long * ) &y;是未定义的行为。使用union。 -
@chux 我认为这段代码早于严格别名规则。
-
@DanielH 我同意你的“这是我看到的唯一 UB”。然而,我们正在冒险 OT。
标签: c