我一直在尝试根据定点数据类型 <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/