[英]Python calculating Catalan Numbers
I have code which is calculating catalan numbers with method of Binominal Coefficients. 我有用二项式系数法计算加泰罗尼亚数的代码。
def BinominalCoefficient(n,k):
res = 1;
if (k > n - k):
k = n - k
for i in range(k):
res *= (n - i)
res /= (i + 1)
return res
def CatalanNumbers(n):
c = BinominalCoefficient(2*n, n)
return (c//(n+1))
print (CatalanNumbers(510))
I have a "nan" result when i try to calculate Catalan number which n is more than 510. Why this is happening? 当我尝试计算n大于510的加泰罗尼亚数字时,我有一个“纳”结果。为什么会发生这种情况? And how can i solve it?
我该如何解决?
I assume you're using Python 3. 我假设您使用的是Python 3。
Your res /= (i + 1)
should be res //= (i + 1)
to force integer arithmetic: 你的
res /= (i + 1)
应该是res //= (i + 1)
来强制整数运算:
def BinominalCoefficient(n,k):
res = 1
if (k > n - k):
k = n - k
for i in range(k):
res *= (n - i)
res //= (i + 1)
return res
def CatalanNumbers(n):
c = BinominalCoefficient(2*n, n)
return (c//(n+1))
print (CatalanNumbers(511))
returns 回报
2190251491739477424254235019785597839694676372955883183976582551028726151813997871354391075304454574949251922785248583970189394756782256529178824038918189668852236486561863197470752363343641524451529091938039960955474280081989297135147411990495428867310575974835605457151854594468879961981363032236839645
You get nan
because the divison /= in Python 3 returns a float which overflows to inf
. 你得到
nan
因为Python 3中的divison / =返回一个溢出到inf
的浮点数。
In addition to xnx's answer , note that starting Python 3.8
, with the addition of math.comb
(binomial coefficient) in the standard library, we can also calculate Catalan numbers as such: 除了xnx的答案之外 ,请注意,在标准库中添加
math.comb
(二项式系数)时,启动Python 3.8
,我们也可以计算加泰罗尼亚语数字:
import math
def catalan(n):
return math.comb(2*n, n) / (n+1)
catalan(511) # 2.1902514917394773e+303
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.