简体   繁体   English

创建加泰罗尼亚数字循环并绘制它 [python]

[英]Creating Catalan number loop and graphing it [python]

Let me preface it with that I am new to python completely and programming for that matter and I need to create a program to print all Catalan numbers up to one trillion.让我先介绍一下,我完全不熟悉 Python 并且为此编程,我需要创建一个程序来打印所有加泰罗尼亚数字,最高可达 1 万亿。 I have the basics of the program written out but I can't seem to understand why I'm not getting the right numbers.我已经写出程序的基础知识,但我似乎无法理解为什么我没有得到正确的数字。 Also I am running into programs when trying to graph the trend out.在尝试绘制趋势图时,我也遇到了程序。 Thanks in advance and here is the code I have:提前致谢,这是我的代码:

import numpy as np
import scipy as sp
from pylab import *

def Catalan(n):
    if n==0:
        return (1)
    elif n==1:
        return (1)
    else:
        return ((4*n+2)/(n+2))*Catalan(n-1)
for n in range(18):
    print (Catalan(n))

n=np.linspace(0,18,100)
y=Catalan(n)
plot(n,y,'r')
show()

There are two main mistakes in your Catalan function.您的 Catalan 函数中有两个主要错误。

First, as seen in http://en.wikipedia.org/wiki/Catalan_number , the formula you wrote is useful to compute Catalan(n+1) in terms of Catalan(n).首先,如http://en.wikipedia.org/wiki/Catalan_number 中所示,您编写的公式对于根据 Catalan(n) 计算 Catalan(n+1) 很有用。 To use it to compute Catalan(n) in terms of Catalan(n-1), as you do, you must shift the index.要使用它根据 Catalan(n-1) 计算 Catalan(n),您必须移动索引。 So it should be (4*n-2)/(n+1)*Catalan(n-1).所以它应该是 (4*n-2)/(n+1)*Catalan(n-1)。

Second, python uses integer arithmetic when dealing with ints.其次,python 在处理整数时使用整数算法。 So, the quotients get rounded down to ints (this is, 5/2 gives 2, not 2.5).因此,商被四舍五入为整数(即​​,5/2 给出 2,而不是 2.5)。 One way to deal with this is to write first the product and then the quotient: (4*n-2)*Catalan(n-1)/(n+1).解决这个问题的一种方法是先写乘积,然后写商:(4*n-2)*Catalan(n-1)/(n+1)。

Nevermind programming, your formula looks broken.没关系编程,你的公式看起来很糟糕。 Take n=2 :n=2

return ((4*n+2)/(n+2))*Catalan(n-1)
     = ((4*2+2)/(2+2))*Catalan(2-1)
     = (( 8 +2)/( 4 ))*Catalan( 1 )
     = (( 10  )/  4  )*    1
     = 2.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM