本文介绍了为什么hypot()函数这么慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 C ++ hypot() Java Math.hypot 。它们似乎都明显慢于 sqrt(a * a + b * b)。这是因为更好的精度吗?什么方法计算斜线 hypot 函数使用?令人惊讶的是,我在文档中找不到任何性能低下的迹象。

I did some testing with C++ hypot() and Java Math.hypot. They both seem to be significantly slower than sqrt(a*a + b*b). Is that because of a better precision? What method to calculate a hypotenuse hypot function uses? Surprisingly I couldn't find any indication of poor performance in the documentation.

推荐答案

这不是一个简单的sqrt函数。您应该检查此链接以实施算法:

It's not a simple sqrt function. You should check this link for the implementation of the algorithm: http://www.koders.com/c/fid7D3C8841ADC384A5F8DE0D081C88331E3909BF3A.aspx

它有while循环以检查收敛

It has while loop to check for convergence

/* Slower but safer algorithm due to Moler and Morrison.  Never
         produces any intermediate result greater than roughly the
         larger of X and Y.  Should converge to machine-precision
         accuracy in 3 iterations.  */

      double r = ratio*ratio, t, s, p = abig, q = asmall;

      do {
        t = 4. + r;
        if (t == 4.)
          break;
        s = r / t;
        p += 2. * s * p;
        q *= s;
        r = (q / p) * (q / p);
      } while (1);

EDIT(从JM更新):

EDIT (Update from J.M):

是原始的Moler-Morrison论文,这里是一个很好的后续由于Dubrulle。

Here is the original Moler-Morrison paper, and here is a nice follow-up due to Dubrulle.

这篇关于为什么hypot()函数这么慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!