Python mpmath不是任意精度吗? [英] Python mpmath not arbitrary precision?
问题描述
我想继续回答上一个问题,即我要使用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:
218922995834555891712
218922995834555891712
这应该是(参考):
218922995834555169169026
218922995834555169026
此处是我的代码:
from mpmath import *
def Phi():
return (1 + sqrt(5)) / 2
def phi():
return (1 - sqrt(5)) / 2
def F(n):
return (power(Phi(), n) - power(phi(), n)) / sqrt(5)
start = 99
end = 100
for x in range(start, end):
print(x, int(F(x)))
推荐答案
mpmath
提供任意精度(如 mpmath.mp.dps $ c $中的设置c>),但计算仍然不准确。例如,
mpmath.sqrt(5)
是不准确的,因此基于此的任何计算也将是不准确的。
mpmath
provides arbitrary precision (as set in mpmath.mp.dps
), but still inaccuate calculation. For example, mpmath.sqrt(5)
is not accurate, so any calculation based on that will also be inaccurate.
要获得 sqrt(5)
的准确结果,您必须使用支持抽象计算的库,例如 http://sympy.org/ 。
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不是任意精度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!