dqpfkzu360216 2012-04-13 12:14
浏览 133
已采纳

javascript中最快的斜边?

I've seen a number of questions about simulations and animations in javascript, which often involve calculating the hypotenuse:

hypot = Math.sqrt(x*x + y*y);

Since cartesian coordinates are the weapon of choice in most of these engines, these calculations are needed to find the distance between pairs of points, etc. So any speedup in calculating the hypotenuse could be a great help to many projects.

To that end, can you see a faster method than the simple implementation above? I found an approximation which was marginally faster in Chrome, but turned out to be much slower in Firefox, based on this approximation function in SuperCollider.

Edit 2015-08-15: I've switched the accepted answer to being the Math.hypot one; I suspect the pragmatic approach at present would be to use Math.hypot or a synthesized hypot function if not available, and to compare against the square (per sch's answer) if that is sufficient and Math.hypot is not available.

  • 写回答

4条回答 默认 最新

  • douzhong1907 2015-06-24 19:22
    关注

    In ECMAScript ES6 you can use Math.hypot:

    // ES5 support
    
    Math.hypot = Math.hypot || function(x, y){ return Math.sqrt(x*x + y*y) }
    
    var x = 3, y = 4;
    
    document.write(Math.hypot(x, y))

    Edit: You can run this test on a blank tab, are 2 million operations with both methods, the results are very good, it is 24% faster.

    var i, tmp, x = 55, y = 66, end, ini = performance.now();
    
    // Math.sqrt operation
    i = 0;
    ini = performance.now();
    tmp = 0;
    while(i++ < 2000000){
        tmp += Math.sqrt(x*x + y*y)
    }
    end = performance.now();
    console.log(tmp, "Math.sqrt operation: " + (end - ini) + " ms");
    
    // Math.hypot
    
    i = 0;
    ini = performance.now();
    tmp = 0;
    while(i++ < 2000000){
        tmp += Math.hypot(x, y)
    }
    end = performance.now();
    
    console.log(tmp, "Math.hypot: " + (end - ini) + " ms");
    

    <kbd>Note</kbd>: In this test, it's used ES6's Math.hypot.

    enter image description here

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据