本文介绍了Python mpmath不是任意精度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想继续回答上一个问题,即我要使用Benet算法计算斐波那契数。为了达到任意精度,我找到了 mpmath
。但是,该实现似乎无法超过一定值。例如,第99个值给出:
I'm trying to continue on my previous question in which I'm trying to calculate Fibonacci numbers using Benet's algorithm. To work with arbitrary precision I found mpmath
. However the implementation seems to fail above certain value. For instance the 99th value gives:
这应该是(。
To get an accurate result for sqrt(5)
, you have to use a library which supports abstract calculation, e.g. http://sympy.org/ .
要获取要获得斐波那契数的准确结果,可能最简单的方法是使用仅执行整数算术的算法。例如:
To get an accurate result for Fibonacci numbers, probably the simplest way is using an algorithm which does only integer arithmetics. For example:
def fib(n):
if n < 0:
raise ValueError
def fib_rec(n):
if n == 0:
return 0, 1
else:
a, b = fib_rec(n >> 1)
c = a * ((b << 1) - a)
d = b * b + a * a
if n & 1:
return d, c + d
else:
return c, d
return fib_rec(n)[0]
这篇关于Python mpmath不是任意精度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!