[英]floating points precision in complicated calculations
For calculating Catalan Numbers, I wrote two codes. 为了计算加泰罗尼亚语数字,我写了两个代码。 One (def "Catalan") works recursively and returns the right Catalan Numbers.
一个(def“ Catalan”)递归工作,并返回正确的加泰罗尼亚数字。
dicatalan = {}
def catalan(n):
if n == 0:
return 1
else:
res = 0
if n not in dicatalan:
for i in range(n):
res += catalan(i) * catalan(n - i - 1)
dicatalan[n] = res
return dicatalan[n]
the other (def "catalanFormula") applies the implicit formula, but doesn't calculate accurately starting from n=30. 另一个(def“ catalanFormula”)应用隐式公式,但从n = 30开始不能正确计算。 the problem derives from floating points - for k=9 the program returns "6835971.999999999" instead of "6835972" and from this moment on accumulates mistakes till the final wrong answer.
问题源自浮点数-对于k = 9,程序返回“ 6835971.999999999”而不是“ 6835972”,并且从这一刻开始累积错误直到最终给出错误答案。
(print line is for checking) (打印行用于检查)
def catalanFormula(n):
result = 1
for k in range(2, n + 1):
result *= ((n + k) / k)
print (result)
return int(result)
I tried rounding and failed, tried Decimal import and still got nothing right. 我尝试四舍五入并失败,尝试了十进制导入,但仍然没有正确的选择。
I need the "catalanFormula" work perfectly as "catalan"; 我需要“ catalanFormula”与“ catalan”完美搭配; Any Ideas?
有任何想法吗?
Thanks! 谢谢!
See the bigfloat package. 参见bigfloat软件包。
from bigfloat import *
setcontext(quadruple_precision)
def catalanFormula(n):
result = BigFloat(1)
for k in range(2, n + 1):
result *= ((BigFloat(n) + BigFloat(k)) / BigFloat(k))
return result
catalanFormula(30)
Output: 输出:
BigFloat.exact('3814986502092304.00000000000000000043', precision=113)
Try calculating the numerator and denominator separately and dividing them at the end. 尝试分别计算分子和分母,最后将它们相除。 If you do this, you should be able to make it a little bit farther with floating-point.
如果这样做,您应该可以使浮点数更远一些。
I'm sure Python has a package for rational numbers. 我确定Python有一个有理数的包。 Using rationals is an even better idea.
使用理性是一个更好的主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.