如何在C++中得到大数的n次方根?
是否有一个 C++ 库可以计算大数的 n 次方根(无法放入 unsigned long long
的数字)?
Is there a C++ library that can take nth roots of big numbers (numbers than can't fit in an unsigned long long
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用 GMP,这是一个流行的开源任意精度数学库。它具有 C++ 绑定。
You can use GMP, a popular open source arbitrary-precision math library. It has C++ bindings.
如果您想自己编写代码,请查看有关 n 根的 Wikipedia 页面:
http://en.wikipedia .org/wiki/Nth_root
迭代算法非常简单:
数字 A 的 n 次根可以通过 n 次根算法计算,这是牛顿法的一个特例。从初始猜测 x(0) 开始,然后使用递推关系进行迭代,
一旦收敛到所需的精度就停止。
If you want to code this yourself, check out the Wikipedia page on nth roots:
http://en.wikipedia.org/wiki/Nth_root
The iterative algorithm is quite simple:
The nth root of a number A can be computed by the nth root algorithm, a special case of Newton's method. Start with an initial guess x(0) and then iterate using the recurrence relation
Stop once you've converged to the desired accuracy.
我猜这取决于你想要比 2^64 大多少。仅使用双精度数就可以达到 10^9 的十分之一。我用 C: 编写了一个测试程序,
产生以下输出:
然后我将每个根与 Wolfram Alpha 进行比较得到我上面引用的错误。
根据您的应用程序,也许这已经足够了。
It depends how much bigger than 2^64 you want to go, I guess. Just using doubles is good to about 1 part in 10^9. I wrote a test program in C:
which produced the following output:
Then I compared with Wolfram Alpha for each root to get the error I quoted above.
Depending on your application, perhaps this will be good enough.
还可以尝试 MAPM 和 qd。
MAPM 用 C 编写,但也有 C++ API。 qd 用 C++ 编写,但也有 C API。
Try also MAPM and qd.
MAPM is written in C but also has a C++ API. qd is written in C++ but also has a C API.
这是一个完美的循环。我每次都能得到准确的答案。
我发现这快了几分钟
Heres a perfect loop for it. I get the exact answer everytime.
I found this to minutes faster
长除法是计算任何正实数的 n 次方根的最佳方法。它给出了计算的每个数字的最佳精度。不需要初始猜测,也不需要迭代近似。
Long division method is the best method to compute the nth root of any positive real number. It gives the best precision of each digit computed. No initial guess and no iterative approximation is required.