快速平方根优化?

use*_*108 19 c optimization

如果您查看这个非常好的页面:

http://www.codeproject.com/Articles/69941/Best-Square-Root-Method-Algorithm-Function-Precisi

你会看到这个程序:

#define SQRT_MAGIC_F 0x5f3759df 
 float  sqrt2(const float x)
{
  const float xhalf = 0.5f*x;

  union // get bits for floating value
  {
    float x;
    int i;
  } u;
  u.x = x;
  u.i = SQRT_MAGIC_F - (u.i >> 1);  // gives initial guess y0
  return x*u.x*(1.5f - xhalf*u.x*u.x);// Newton step, repeating increases accuracy 
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:有没有特别的理由为什么这不实现为:

#define SQRT_MAGIC_F 0x5f3759df 
 float  sqrt2(const float x)
{

  union // get bits for floating value
  {
    float x;
    int i;
  } u;
  u.x = x;
  u.i = SQRT_MAGIC_F - (u.i >> 1);  // gives initial guess y0

  const float xux = x*u.x;

  return xux*(1.5f - .5f*xux*u.x);// Newton step, repeating increases accuracy 
}
Run Code Online (Sandbox Code Playgroud)

因为,从拆卸,我看到MUL少一个.有什么目的可以xhalf出现吗?

egu*_*gur 4

当乘法器在最后一行作为中间结果保存在 80 位寄存器中链接在一起时,使用 80 位寄存器的传统浮点数学可能会更准确。

上层实现中的第一个乘法与随后的整数数学并行发生,它们使用不同的执行资源。另一方面,第二个函数看起来更快,但很难判断它是否真的是因为上述原因。另外,const float xux = x*ux; 语句将结果减少回 32 位浮点数,这可能会降低整体精度。

您可以直接测试这些函数并将它们与math.h 中的sqrt函数进行比较(使用 double 而不是 float)。这样您就可以看到哪个更快、哪个更准确。