知乎上看到的,一个神奇的算法

2015-04-07 21:15:38 +08:00
 EchoChan
http://www.zhihu.com/question/29214128/answer/44063508

提及的算法:
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;
}


只想说,什么人才能想到这啊?
2641 次点击
所在节点    分享发现
8 条回复
xenme
2015-04-07 21:32:54 +08:00
est
2015-04-07 21:41:44 +08:00
这还能从知呼看。。LZ是多久没看技术新闻了。。。。。。。。。
EchoChan
2015-04-07 21:47:23 +08:00
@est 真的是新手啊,大三而已。。。

@xenme 谢谢。
Quaintjade
2015-04-07 21:59:26 +08:00
很老的文章了,知乎不要指望看到多少新鲜的东西。

话说多少人出了学校就忘了牛顿迭代法,有时编程时还挺有用的。
EchoChan
2015-04-07 22:01:34 +08:00
@Quaintjade 我表示还真没学过牛顿迭代法
bcxx
2015-04-07 22:03:34 +08:00
@EchoChan 高中数学应该就有讲过啊
EchoChan
2015-04-07 22:19:19 +08:00
@bcxx 冏了,原来是迭代。。。
sneezry
2015-04-07 23:24:26 +08:00
function sqrt(number){
if(number <= 0){
return 0;
}
var buf = new ArrayBuffer(4);
var floatBuf = new Float32Array(buf);
floatBuf[0] = number;
var intBuf = new Int32Array(buf);
intBuf[0] = 0x1fbd1df5 + (intBuf[0]>>1);
return 0.5*(floatBuf[0]+number/floatBuf[0]);
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/182197

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX