c++ - 从不动点计算平方根

标签 c++ fixed-point square-root

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

最佳答案

这是一个 python 原型(prototype),展示了如何在不动点上求平方根 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 位类型,否则它将在 <<8 上溢出位步。还要注意 //是 python 中的整数除法。

关于c++ - 从不动点计算平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16891496/

相关文章:

java - 关于 IF 语句

c - 如何在 C 中打印负数的平方根并显示 i

c - 使用 Newton-Raphson 方法在 C 中求平方根

c++ - 切换菜单计算器不会显示算术

C++ : auto variable deduction differs range for loop vs a normal for loop for multi dimensional array

c++ - 分解 D3DXMatrixLookAtLH 矩阵

C++:二叉树所有节点值的总和

c++ - .cpp 文件中的两个 namespace 用于比较

precision - Ada 定点类型的限制

c++ - C/C++ 中的定点奇异值分解