gpt4 book ai didi

c - 快速平方根优化?

转载 作者:太空狗 更新时间:2023-10-29 16:28:55 24 4
gpt4 key购买 nike

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

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
}

我的问题是:是否有任何特殊原因导致未将其实现为:

#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
}

因为,从反汇编中,我看到一个 MUL 少了。让 xhalf 出现有什么意义吗?

最佳答案

使用 80 位寄存器的遗留 float 学可能在最后一行链接在一起的乘数作为中间结果保存在 80 位寄存器中时更准确。

上层实现中的第一个乘法与后面的整数数学运算并行进行,它们使用不同的执行资源。另一方面,第二个函数看起来更快,但很难判断是否真的是因为上述原因。此外,const float xux = x*u.x; 语句将结果还原为 32 位 float ,这可能会降低整体准确性。

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

关于c - 快速平方根优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19542275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com