如何改善小数点固定平方根的计算方法

13
我正在使用Anthony Williams的固定点库,该库在Dr Dobb's文章“使用固定点算术优化数学密集型应用程序”中进行了描述,使用Rhumb Line方法计算两个地理点之间的距离。

当两点之间的距离很大时(大于几公里),这种方法运行良好,但在较小的距离下效果非常差。最坏的情况是两点相等或接近相等,结果是194米的距离,而我需要在距离大于或等于1米时至少有1米的精度。
与双精度浮点实现相比,我发现问题出在fixed::sqrt()函数上,在小值时性能表现不佳:
x       std::sqrt(x)    fixed::sqrt(x)  error
----------------------------------------------------
0       0               3.05176e-005    3.05176e-005
1e-005  0.00316228      0.00316334      1.06005e-006
2e-005  0.00447214      0.00447226      1.19752e-007
3e-005  0.00547723      0.0054779       6.72248e-007
4e-005  0.00632456      0.00632477      2.12746e-007
5e-005  0.00707107      0.0070715       4.27244e-007
6e-005  0.00774597      0.0077467       7.2978e-007
7e-005  0.0083666       0.00836658      1.54875e-008
8e-005  0.00894427      0.00894427      1.085e-009

对于fixed::sqrt(0)的结果进行修正非常简单,只需将其视为特殊情况即可,但这并不能解决小非零距离的问题,误差从194米开始,随着距离增加而收敛于零。我可能需要在精度方面向零至少提高一个数量级。

fixed::sqrt()算法在上述链接的第4页中简要说明,但我很难理解它,更不用说确定是否可以改进它了。函数的代码如下:

fixed fixed::sqrt() const
{
    unsigned const max_shift=62;
    uint64_t a_squared=1LL<<max_shift;
    unsigned b_shift=(max_shift+fixed_resolution_shift)/2;
    uint64_t a=1LL<<b_shift;

    uint64_t x=m_nVal;

    while(b_shift && a_squared>x)
    {
        a>>=1;
        a_squared>>=2;
        --b_shift;
    }

    uint64_t remainder=x-a_squared;
    --b_shift;

    while(remainder && b_shift)
    {
        uint64_t b_squared=1LL<<(2*b_shift-fixed_resolution_shift);
        int const two_a_b_shift=b_shift+1-fixed_resolution_shift;
        uint64_t two_a_b=(two_a_b_shift>0)?(a<<two_a_b_shift):(a>>-two_a_b_shift);

        while(b_shift && remainder<(b_squared+two_a_b))
        {
            b_squared>>=2;
            two_a_b>>=1;
            --b_shift;
        }
        uint64_t const delta=b_squared+two_a_b;
        if((2*remainder)>delta)
        {
            a+=(1LL<<b_shift);
            remainder-=delta;
            if(b_shift)
            {
                --b_shift;
            }
        }
    }
    return fixed(internal(),a);
}

请注意,m_nVal 是内部固定点表示值,它是一个int64_t,并且表示使用Q36.28格式(fixed_resolution_shift = 28)。表示本身具有足够的精度,至少可达到8位小数,并且作为赤道弧的分数适用于约0.14米的距离,因此限制不在于固定点表示。

在此应用中,使用航向线方法是标准机构的建议,因此无法更改,而且在任何情况下,可能需要在应用程序的其他地方或未来的应用程序中使用更准确的平方根函数。

问题:是否可以提高fixed::sqrt()算法对小非零值的准确性,同时仍保持其有界和确定性收敛?

附加信息:用于生成上述表格的测试代码:

#include <cmath>
#include <iostream>
#include "fixed.hpp"

int main()
{
    double error = 1.0 ;
    for( double x = 0.0; error > 1e-8; x += 1e-5 )
    {
        double fixed_root = sqrt(fixed(x)).as_double() ;
        double std_root = std::sqrt(x) ;
        error = std::fabs(fixed_root - std_root) ;
        std::cout << x << '\t' << std_root << '\t' << fixed_root << '\t' << error << std::endl ;
    }
}

结论 根据Justin Peel的解决方案和分析,以及与“固定点算术的被忽视艺术”中的算法进行比较,我已将后者改编为以下形式:

fixed fixed::sqrt() const
{
    uint64_t a = 0 ;            // root accumulator
    uint64_t remHi = 0 ;        // high part of partial remainder
    uint64_t remLo = m_nVal ;   // low part of partial remainder
    uint64_t testDiv ;
    int count = 31 + (fixed_resolution_shift >> 1); // Loop counter
    do 
    {
        // get 2 bits of arg
        remHi = (remHi << 2) | (remLo >> 62); remLo <<= 2 ;

        // Get ready for the next bit in the root
        a <<= 1;   

        // Test radical
        testDiv = (a << 1) + 1;    
        if (remHi >= testDiv) 
        {
            remHi -= testDiv;
            a += 1;
        }

    } while (count-- != 0);

    return fixed(internal(),a);
}

虽然这提供了更高的精度,但我需要的改进并没有实现。 Q36.28格式仅提供了我所需的精度,但是无法执行sqrt()而不会失去一些精度位。 但是,一些侧面思考提供了更好的解决方案。 我的应用程序将计算出的距离与某个距离限制进行比较。 很明显的解决方案是测试距离的平方是否小于限制的平方!


Clifford - 文章的 URL 似乎出现了问题(需要 UBM Techweb 登录,你可能已经登录并没有遇到这个问题)。我尝试在其他地方找到文章,但没有找到 - Google 缓存似乎是最好的选择。首先感谢您引用了这篇文章。 - Dan
@Dan,我访问了原始链接并没有遇到问题。我从未使用过UBM,也不认为我已登录DDJ,所以我不知道为什么会出现问题。 - Mark Ransom
我已经使用这段代码几年了;我可能是在登录要求之前下载的库。从安东尼自己的网站获取它。 - Clifford
@MarkRansom - 好的,我不得不查一下...我有来自drdobbs/ubm/ddj的cookies,一旦我删除它们,它就让我通过而不强制我登录。很好,让你的注册用户面临更多的障碍。 - Dan
你是如何从fixed::sqrt()获取表格中显示的数字的?你使用了哪种编译器+操作系统?除了0的平方根之外,我得到的数字都不一样。无论是使用gcc(DJGPP/DOS)还是Open Watcom(Windows),我的结果都与表格中的x相差约10^-5到10^-6。当您填写表格时,您是否使用了超过28位的小数位?您是如何转换成/从fixed的?您的浮点类型大小是多少(顺便问一下,它是double还是long double)? - Alexey Frunze
显示剩余2条评论
4个回答

12

假设 sqrt(ab) = sqrt(a)sqrt(b),那么你是不是可以只针对数字较小的情况进行特殊处理,将其左移给定的比特数,计算平方根,再向右移回原来的位置一半得到结果?

即:

 sqrt(n) = sqrt(n.2^k)/sqrt(2^k)
         = sqrt(n.2^k).2^(-k/2)

例如,当n小于2^8时,请选择k = 28。


非常聪明和高效的解决方案。 - Jim Clay

4
原始实现显然存在一些问题。我尝试使用当前的代码修复所有问题,但最终感到沮丧,采取了不同的方法。现在我可能可以修复原始代码,但我更喜欢我的方法。
我将输入数字视为起始处于Q64中,这与向左移动28位然后向右移动14位(平方根将其减半)相同。但是,如果只是这样做,则精度将限制为1/2^14 = 6.1035e-5,因为最后14位将为0。为了解决这个问题,我正确地移动了a和余数,并为了填充数字而再次执行循环。代码可以更有效且更清晰,但我会把它留给别人。下面显示的精度几乎是使用Q36.28获得的最佳精度。如果将固定点sqrt与输入数字的浮点数sqrt进行比较(在将其转换为固定点并返回之后),则误差约为2e-9(我没有在下面的代码中执行此操作,但需要更改一行)。这与Q36.28的最佳精度完全一致,即1/2^28 = 3.7529e-9。
顺便说一句,原始代码中的一个大错误是从未考虑m = 0的术语,因此该位永远无法设置。无论如何,这是代码。享受吧!
#include <iostream>
#include <cmath>

typedef unsigned long uint64_t;

uint64_t sqrt(uint64_t in_val)
{
    const uint64_t fixed_resolution_shift = 28;
    const unsigned max_shift=62;
    uint64_t a_squared=1ULL<<max_shift;
    unsigned b_shift=(max_shift>>1) + 1;
    uint64_t a=1ULL<<(b_shift - 1);

    uint64_t x=in_val;

    while(b_shift && a_squared>x)
    {
        a>>=1;
        a_squared>>=2;
        --b_shift;
    }

    uint64_t remainder=x-a_squared;
    --b_shift;

    while(remainder && b_shift)
    {
        uint64_t b_squared=1ULL<<(2*(b_shift - 1));
        uint64_t two_a_b=(a<<b_shift);

        while(b_shift && remainder<(b_squared+two_a_b))
        {
            b_squared>>=2;
            two_a_b>>=1;
            --b_shift;
        }
        uint64_t const delta=b_squared+two_a_b;
        if((remainder)>=delta && b_shift)
        {
            a+=(1ULL<<(b_shift - 1));
            remainder-=delta;
            --b_shift;
        }
    }
    a <<= (fixed_resolution_shift/2);
    b_shift = (fixed_resolution_shift/2) + 1;
    remainder <<= (fixed_resolution_shift);

    while(remainder && b_shift)
    {
        uint64_t b_squared=1ULL<<(2*(b_shift - 1));
        uint64_t two_a_b=(a<<b_shift);

        while(b_shift && remainder<(b_squared+two_a_b))
        {
            b_squared>>=2;
            two_a_b>>=1;
            --b_shift;
        }
        uint64_t const delta=b_squared+two_a_b;
        if((remainder)>=delta && b_shift)
        {
            a+=(1ULL<<(b_shift - 1));
            remainder-=delta;
            --b_shift;
        }
    }

    return a;
}

double fixed2float(uint64_t x)
{
    return static_cast<double>(x) * pow(2.0, -28.0);
}

uint64_t float2fixed(double f)
{
    return static_cast<uint64_t>(f * pow(2, 28.0));
}

void finderror(double num)
{
    double root1 = fixed2float(sqrt(float2fixed(num)));
    double root2 = pow(num, 0.5);
    std::cout << "input: " << num << ", fixed sqrt: " << root1 << " " << ", float sqrt: " << root2 << ", finderror: " << root2 - root1 << std::endl;
}

main()
{
    finderror(0);
    finderror(1e-5);
    finderror(2e-5);
    finderror(3e-5);
    finderror(4e-5);
    finderror(5e-5);
    finderror(pow(2.0,1));
    finderror(1ULL<<35);
}

程序的输出结果为:
input: 0, fixed sqrt: 0 , float sqrt: 0, finderror: 0
input: 1e-05, fixed sqrt: 0.00316207 , float sqrt: 0.00316228, finderror: 2.10277e-07
input: 2e-05, fixed sqrt: 0.00447184 , float sqrt: 0.00447214, finderror: 2.97481e-07
input: 3e-05, fixed sqrt: 0.0054772 , float sqrt: 0.00547723, finderror: 2.43815e-08
input: 4e-05, fixed sqrt: 0.00632443 , float sqrt: 0.00632456, finderror: 1.26255e-07
input: 5e-05, fixed sqrt: 0.00707086 , float sqrt: 0.00707107, finderror: 2.06055e-07
input: 2, fixed sqrt: 1.41421 , float sqrt: 1.41421, finderror: 1.85149e-09
input: 3.43597e+10, fixed sqrt: 185364 , float sqrt: 185364, finderror: 2.24099e-09

这正是我所要求的,而且更或多或少是现有代码体的替代品。不幸的是,我对所需精度的估计是错误的,即使有了这个巨大的改进,仍然不足。这提高了sqrt()在其他地方使用时的准确性,因此我可能会保留它。我将进一步研究它以进行尽职调查,但如果像你所说这是性能的限制,在这种情况下我将不得不使用std::sqrt()和浮点数。 - Clifford
我将这个算法的结果与*"The Neglected Art of Fixed Point Arithmetic"*中的算法进行了比较,发现两者产生了相同的结果,而且可能是你所提到的更有效率/更清晰的版本。你至少让我意识到了Q36.28的限制。谢谢。 - Clifford

1

我不确定您是如何从表格中显示的fixed::sqrt()获取数字的。

这是我的做法:

#include <stdio.h>
#include <math.h>

#define __int64 long long // gcc doesn't know __int64
typedef __int64 fixed;

#define FRACT 28

#define DBL2FIX(x) ((fixed)((double)(x) * (1LL << FRACT)))
#define FIX2DBL(x) ((double)(x) / (1LL << FRACT))

// De-++-ified code from
// http://www.justsoftwaresolutions.co.uk/news/optimizing-applications-with-fixed-point-arithmetic.html
fixed sqrtfix0(fixed num)
{
    static unsigned const fixed_resolution_shift=FRACT;

    unsigned const max_shift=62;
    unsigned __int64 a_squared=1LL<<max_shift;
    unsigned b_shift=(max_shift+fixed_resolution_shift)/2;
    unsigned __int64 a=1LL<<b_shift;

    unsigned __int64 x=num;

    unsigned __int64 remainder;

    while(b_shift && a_squared>x)
    {
        a>>=1;
        a_squared>>=2;
        --b_shift;
    }

    remainder=x-a_squared;
    --b_shift;

    while(remainder && b_shift)
    {
        unsigned __int64 b_squared=1LL<<(2*b_shift-fixed_resolution_shift);
        int const two_a_b_shift=b_shift+1-fixed_resolution_shift;
        unsigned __int64 two_a_b=(two_a_b_shift>0)?(a<<two_a_b_shift):(a>>-two_a_b_shift);
        unsigned __int64 delta;

        while(b_shift && remainder<(b_squared+two_a_b))
        {
            b_squared>>=2;
            two_a_b>>=1;
            --b_shift;
        }
        delta=b_squared+two_a_b;
        if((2*remainder)>delta)
        {
            a+=(1LL<<b_shift);
            remainder-=delta;
            if(b_shift)
            {
                --b_shift;
            }
        }
    }
    return (fixed)a;
}

// Adapted code from
// http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Digit-by-digit_calculation
fixed sqrtfix1(fixed num)
{
    fixed res = 0;
    fixed bit = (fixed)1 << 62; // The second-to-top bit is set
    int s = 0;

    // Scale num up to get more significant digits

    while (num && num < bit)
    {
        num <<= 1;
        s++;
    }

    if (s & 1)
    {
        num >>= 1;
        s--;
    }

    s = 14 - (s >> 1);

    while (bit != 0)
    {
        if (num >= res + bit)
        {
            num -= res + bit;
            res = (res >> 1) + bit;
        }
        else
        {
            res >>= 1;
        }

        bit >>= 2;
    }

    if (s >= 0) res <<= s;
    else res >>= -s;

    return res;
}

int main(void)
{
    double testData[] =
    {
        0,
        1e-005,
        2e-005,
        3e-005,
        4e-005,
        5e-005,
        6e-005,
        7e-005,
        8e-005,
    };
    int i;

    for (i = 0; i < sizeof(testData) / sizeof(testData[0]); i++)
    {
        double x = testData[i];
        fixed xf = DBL2FIX(x);

        fixed sqf0 = sqrtfix0(xf);
        fixed sqf1 = sqrtfix1(xf);

        double sq0 = FIX2DBL(sqf0);
        double sq1 = FIX2DBL(sqf1);

        printf("%10.8f:  "
               "sqrtfix0()=%10.8f / err=%e  "
               "sqrt()=%10.8f  "
               "sqrtfix1()=%10.8f / err=%e\n",
               x,
               sq0, fabs(sq0 - sqrt(x)),
               sqrt(x),
               sq1, fabs(sq1 - sqrt(x)));
    }

    printf("sizeof(double)=%d\n", (int)sizeof(double));

    return 0;
}

这是我使用gcc和Open Watcom得到的结果:

0.00000000:  sqrtfix0()=0.00003052 / err=3.051758e-05  sqrt()=0.00000000  sqrtfix1()=0.00000000 / err=0.000000e+00
0.00001000:  sqrtfix0()=0.00311279 / err=4.948469e-05  sqrt()=0.00316228  sqrtfix1()=0.00316207 / err=2.102766e-07
0.00002000:  sqrtfix0()=0.00445557 / err=1.656955e-05  sqrt()=0.00447214  sqrtfix1()=0.00447184 / err=2.974807e-07
0.00003000:  sqrtfix0()=0.00543213 / err=4.509667e-05  sqrt()=0.00547723  sqrtfix1()=0.00547720 / err=2.438148e-08
0.00004000:  sqrtfix0()=0.00628662 / err=3.793423e-05  sqrt()=0.00632456  sqrtfix1()=0.00632443 / err=1.262553e-07
0.00005000:  sqrtfix0()=0.00701904 / err=5.202484e-05  sqrt()=0.00707107  sqrtfix1()=0.00707086 / err=2.060551e-07
0.00006000:  sqrtfix0()=0.00772095 / err=2.501943e-05  sqrt()=0.00774597  sqrtfix1()=0.00774593 / err=3.390476e-08
0.00007000:  sqrtfix0()=0.00836182 / err=4.783859e-06  sqrt()=0.00836660  sqrtfix1()=0.00836649 / err=1.086198e-07
0.00008000:  sqrtfix0()=0.00894165 / err=2.621519e-06  sqrt()=0.00894427  sqrtfix1()=0.00894409 / err=1.777289e-07
sizeof(double)=8

编辑:

我错过了上面的sqrtfix1()无法处理大参数的事实。可以通过在参数末尾添加28个零并基本计算该数的精确整数平方根来修复它。这将以使用128位算术进行内部计算为代价,但这很简单:

fixed sqrtfix2(fixed num)
{
    unsigned __int64 numl, numh;
    unsigned __int64 resl = 0, resh = 0;
    unsigned __int64 bitl = 0, bith = (unsigned __int64)1 << 26;

    numl = num << 28;
    numh = num >> (64 - 28);

    while (bitl | bith)
    {
        unsigned __int64 tmpl = resl + bitl;
        unsigned __int64 tmph = resh + bith + (tmpl < resl);

        tmph = numh - tmph - (numl < tmpl);
        tmpl = numl - tmpl;

        if (tmph & 0x8000000000000000ULL)
        {
            resl >>= 1;
            if (resh & 1) resl |= 0x8000000000000000ULL;
            resh >>= 1;
        }
        else
        {
            numl = tmpl;
            numh = tmph;

            resl >>= 1;
            if (resh & 1) resl |= 0x8000000000000000ULL;
            resh >>= 1;

            resh += bith + (resl + bitl < resl);
            resl += bitl;
        }

        bitl >>= 2;
        if (bith & 1) bitl |= 0x4000000000000000ULL;
        if (bith & 2) bitl |= 0x8000000000000000ULL;
        bith >>= 2;
    }

    return resl;
}

它提供的结果与这个答案几乎相同(对于3.43597e+10略微更好):

0.00000000:  sqrtfix0()=0.00003052 / err=3.051758e-05  sqrt()=0.00000000  sqrtfix2()=0.00000000 / err=0.000000e+00
0.00001000:  sqrtfix0()=0.00311279 / err=4.948469e-05  sqrt()=0.00316228  sqrtfix2()=0.00316207 / err=2.102766e-07
0.00002000:  sqrtfix0()=0.00445557 / err=1.656955e-05  sqrt()=0.00447214  sqrtfix2()=0.00447184 / err=2.974807e-07
0.00003000:  sqrtfix0()=0.00543213 / err=4.509667e-05  sqrt()=0.00547723  sqrtfix2()=0.00547720 / err=2.438148e-08
0.00004000:  sqrtfix0()=0.00628662 / err=3.793423e-05  sqrt()=0.00632456  sqrtfix2()=0.00632443 / err=1.262553e-07
0.00005000:  sqrtfix0()=0.00701904 / err=5.202484e-05  sqrt()=0.00707107  sqrtfix2()=0.00707086 / err=2.060551e-07
0.00006000:  sqrtfix0()=0.00772095 / err=2.501943e-05  sqrt()=0.00774597  sqrtfix2()=0.00774593 / err=3.390476e-08
0.00007000:  sqrtfix0()=0.00836182 / err=4.783859e-06  sqrt()=0.00836660  sqrtfix2()=0.00836649 / err=1.086198e-07
0.00008000:  sqrtfix0()=0.00894165 / err=2.621519e-06  sqrt()=0.00894427  sqrtfix2()=0.00894409 / err=1.777289e-07
2.00000000:  sqrtfix0()=1.41419983 / err=1.373327e-05  sqrt()=1.41421356  sqrtfix2()=1.41421356 / err=1.851493e-09
34359700000.00000000:  sqrtfix0()=185363.69654846 / err=5.097361e-06  sqrt()=185363.69655356  sqrtfix2()=185363.69655356 / err=1
.164153e-09

0
很多年前,我曾经为我们公司开发的一台小型计算机编写了一个演示程序。这台计算机内置了一个平方根指令,我们编写了一个简单的程序来演示计算机对TTY进行16位加/减/乘/除/平方根操作。可惜,后来发现平方根指令存在严重的错误,但我们已经答应演示该功能。因此,我们创建了一个包含值1-255的平方数数组,然后使用简单的查找来匹配输入值与数组值之一。索引即为所求平方根。

不幸的是,我需要更好的精度覆盖更广泛的范围,这是使用查找表无法实现的。 - Clifford

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接