【问题标题】:Computing square root from fixed point从不动点计算平方根
【发布时间】:2013-06-03 06:58:18
【问题描述】:

我一直在尝试从定点数据类型<24,8> 计算平方根。
不幸的是,似乎没有任何效果。
有谁知道如何在 C(++) 中快速高效地做到这一点)?

【问题讨论】:

  • 您到底尝试了什么,结果如何?
  • 查找 Newton-Raphson。应该在几次迭代中给你一个合理的结果。
  • Djon,我尝试了 Newton-Raphson 方法。我会更深入地研究这个! Mats Petersson 感谢您的建议!

标签: c++ fixed-point square-root


【解决方案1】:

这是一个python原型,展示了如何在定点using Newton's method.做平方根

import math

def sqrt(n, shift=8):
     """
     Return the square root of n as a fixed point number.  It uses a
     second order Newton-Raphson convergence.  This doubles the number
     of significant figures on each iteration.

     Shift is the number of bits in the fractional part of the fixed
     point number.
     """
     # Initial guess - could do better than this
     x = 1 << shift // 32 bit type
     n_one = n << shift // 64 bit type
     while 1:
         x_old = x
         x = (x + n_one // x) // 2
         if x == x_old:
             break
     return x

def main():
    a = 4.567
    print "Should be", math.sqrt(a)
    fp_a = int(a * 256)
    print "With fixed point", sqrt(fp_a)/256.

if __name__ == "__main__":
    main()

在将其转换为 C++ 时,请务必注意类型 - 特别是 n_one 需要是 64 位类型,否则它将在 &lt;&lt;8 位步骤上溢出。另请注意,// 在 python 中是一个整数除法。

【讨论】:

  • 很奇怪。据我了解,牛顿拉普森方法的工作原理是 f(x) = x0 - f(x)/f'(x)。我在这里看不到那个功能。我看到你的 x0 是 1。你在用 n_one 做什么?你能发布一些关于这段代码的解释吗?
  • @newbie_old 如果你计算出 sqrt 的微分并代入上面的等式并简化,你会得到 x(i+1) = (x(i) + n/x(i))/2 其中n 是你试图平方根的数字。 n_onen 移位了shift 位,表示定点世界中的n
  • 但是 n_one 已经是定点格式了,不是吗?我看到你将它与 256 相乘,这是 1
  • @newbie_old 我明白你的意思,我上面的解释不正确。 n_one 实际上是n * one²,即n_float &lt;&lt; 16,所以当你将它除以x 时,x_float * one = x_float &lt;&lt; 8 你会得到(n_float/x_float) * one = (n_float/x_float) &lt;&lt; 8,这是正确归一化的,但具有完整的精度该部门的。我希望现在说得通!
猜你喜欢
  • 1970-01-01
  • 2021-08-03
  • 2013-04-01
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多