2010-04-08 69 views

回答

10

您可以使用GMP,一个流行的开源任意精度数学库。它有C++ bindings

+1

是的,特别是函数mpz_root。 – 2010-04-08 23:32:54

4

如果你想这个自己的代码,请查看维基百科页面上的第n根:

http://en.wikipedia.org/wiki/Nth_root

的迭代算法很简单:

许多A级的N次方根可由第n个根算法计算,牛顿法的一个特例。开始的初始猜测X(0),然后使用迭代递推关系

x(k+1) = [(n - 1) * x(k) + A/x(k)^(n - 1)]/n 

停止,一旦你已经收敛到所需的精度。

2

这取决于你想要走多远大于2^64,我想。在10^9的时候使用双打大约是1分。我在C写一个测试程序:

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

int main(int argc, char **argv) 
{ 
    unsigned long long x; 
    double dx; 
    int i; 

    //make x the max possible value 
    x = ~0ULL; 
    dx = (double)x; 
    printf("Starting with dx = %f\n", dx); 
    //print the 2th to 20th roots 
    for (i = 2; i < 21; i++) 
    { 
     printf("%dth root %.15f\n", i, pow(dx, 1.0/i)); 
    } 
    return 0; 
} 

其产生以下输出:

Starting with dx = 18446744073709551616.000000 
2th root 4294967296.000000000000000 
3th root 2642245.949629130773246 
4th root 65536.000000000000000 
5th root 7131.550214521852467 
6th root 1625.498677215435691 
7th root 565.293831000991759 
8th root 256.000000000000000 
9th root 138.247646578215154 
10th root 84.448506289465257 
11th root 56.421840319745364 
12th root 40.317473596635935 
13th root 30.338480458853493 
14th root 23.775908626191171 
15th root 19.248400577313866 
16th root 16.000000000000000 
17th root 13.592188707483222 
18th root 11.757875938204789 
19th root 10.327513583579238 
20th root 9.189586839976281 

然后我与Wolfram Alpha每个根得到我上面引述的错误比较。

根据您的应用程序,也许这将是足够好的。

+0

请注意,设置所有位的标准方式是'〜'运算符,即''x =〜0ULL' – MSalters 2010-04-08 09:16:40

+0

@MSalters - 我的脸,它是红色的。谢谢。 – mtrw 2010-04-08 21:01:04

0

请尝试MAPMqd

MAPM是用C编写的,但也有一个C++ API。 qd是用C++编写的,但也有一个C API。

0

长分法是计算任何正实数的第n个根的最佳方法。它给出了计算出的每个数字的最佳精度。不需要初始猜测,也不需要迭代逼近。

+2

一个例子值得千言万语...... – 2016-02-17 11:23:21

+0

虽然这可能是一个有价值的提示来解决问题,但一个好的答案也说明了解决方案。请[编辑]提供示例代码来展示你的意思。或者,可以考虑将其写为注释。 – 2017-05-10 14:25:02

相关问题