【问题标题】:Square root source code found on the net网上找到的平方根源代码
【发布时间】:2017-07-17 16:08:55
【问题描述】:

我正在寻找一些用于平方根计算的算法,并找到了这个源文件。我想尝试复制它,因为它看起来很简单,但我无法将它与某些已知算法(牛顿、巴比伦......)联系起来。能告诉我名字吗?

int sqrt(int num) {
    int op = num;
    int res = 0;
    int one = 1 << 30; // The second-to-top bit is set: 1L<<30 for long

    // "one" starts at the highest power of four <= the argument.
    while (one > op)
        one >>= 2;

    while (one != 0) {
        if (op >= res + one) {
            op -= res + one;
            res += 2 * one;
        }
        res >>= 1;
        one >>= 2;
    }
    return res;
}

【问题讨论】:

标签: c algorithm square-root


【解决方案1】:

正如@Eugene Sh. 所引用的,这是计算平方根的经典“逐位”方法。在小学教这些东西的时候,在base 10学到了。

OP 的代码也无法选择数字。 sqrt(1073741824) --&gt; -1 而不是预期的 32768。1073741824 == 0x40000000。此外,它失败了大多数(所有?)价值这个和更大的。当然OP的sqrt(some_negative)也是个问题。

候选替代:也here

unsigned isqrt(unsigned num) {
  unsigned res = 0;

  // The second-to-top bit is set: 1 << 30 for 32 bits
  // Needs work to run on unusual platforms where `unsigned` has padding or odd bit width.
  unsigned bit = 1u << (sizeof(num) * CHAR_BIT - 2); 

  // "bit" starts at the highest power of four <= the argument.
  while (bit > num)
    bit >>= 2;

  while (bit > 0) {
    if (num >= res + bit) {
      num -= res + bit;
      res = (res >> 1) + bit;  // Key dif between this and OP's code
    } else {
      res >>= 1;
    }
    bit >>= 2;
  }
  return res;
}

便携性更新。需要 4 的最大幂。

#include <limits.h>
// greatest power of 4 <= a power-of-2 minus 1
#define POW4_LE_POW2M1(n) (  ((n)/2 + 1) >> ((n)%3==0)  )

unsigned bit = POW4_LE_POW2M1(UINT_MAX);

【讨论】:

    猜你喜欢
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 2011-09-14
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    相关资源
    最近更新 更多