2010-04-08 65 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

相關問題