V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
EchoChan
V2EX  ›  分享发现

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

  •  
  •   EchoChan · 2015-04-07 21:15:38 +08:00 · 2623 次点击
    这是一个创建于 3319 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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;
    }


    只想说,什么人才能想到这啊?
    xenme
        1
    xenme  
       2015-04-07 21:32:54 +08:00
    est
        2
    est  
       2015-04-07 21:41:44 +08:00
    这还能从知呼看。。LZ是多久没看技术新闻了。。。。。。。。。
    EchoChan
        3
    EchoChan  
    OP
       2015-04-07 21:47:23 +08:00
    @est 真的是新手啊,大三而已。。。

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

    话说多少人出了学校就忘了牛顿迭代法,有时编程时还挺有用的。
    EchoChan
        5
    EchoChan  
    OP
       2015-04-07 22:01:34 +08:00
    @Quaintjade 我表示还真没学过牛顿迭代法
    bcxx
        6
    bcxx  
       2015-04-07 22:03:34 +08:00
    @EchoChan 高中数学应该就有讲过啊
    EchoChan
        7
    EchoChan  
    OP
       2015-04-07 22:19:19 +08:00
    @bcxx 冏了,原来是迭代。。。
    sneezry
        8
    sneezry  
       2015-04-07 23:24:26 +08:00   ❤️ 1
    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]);
    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1576 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:20 · PVG 01:20 · LAX 10:20 · JFK 13:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.