简体   繁体   English

使用Python计算加泰罗尼亚语?

[英]Catalan number calculation using Python?

I am writing a Python code to generate Catalan numbers using the mathematical formula given here: 我正在编写Python代码,使用此处给出的数学公式生成加泰罗尼亚语数字:

C(0) = 1 and C(n) = (2(2n − 1) / (n + 1)) * C(n − 1) per this website here. C(0)= 1且C(n)=(2(2n − 1)/(n + 1))* C(n − 1)每个网站。 ( https://rosettacode.org/wiki/Catalan_numbers ) https://rosettacode.org/wiki/Catalan_numbers

However, when I am writing it in python as a function, it gives me false results. 但是,当我用python作为函数编写它时,它给了我错误的结果。

eg: For 20 answer should be 6564120420.0 while my code gives me 344373768. 例如:20的答案应该是6564120420.0,而我的代码给了我344373768。

Here: 这里:

def catalan(cat_input):

    if cat_input==0:
    return 1 

    else:
    return  (((4*cat_input) - 2) / (cat_input + 1)) * (catalan(cat_input-1))

Can someone help me figure this out please ? 有人可以帮我解决这个问题吗?

The problem is when dividing / . 问题是在除/ As-is the result (of the division itself, before multiplying) may not be whole number, and since / in python2 is by default int-division the decimal part gets "cropped" and you get the wrong results. 照原样(乘除之前,除法本身)的结果可能不是整数,并且由于python2中的/默认为int-division,因此小数部分被“裁剪”,并且您得到了错误的结果。

There are couple ways to fix that (pick your favorite): 有几种解决方法(选择您喜欢的方法):

  • Change the order in the equation, instead of (((4*cat_input) - 2) / (cat_input + 1)) * (catalan(cat_input-1)) use (((4*cat_input) - 2) * (catalan(cat_input-1)) / (cat_input + 1)) , that way you are guaranteed to get whole number after division 更改方程式的顺序,而不是(((4*cat_input) - 2) / (cat_input + 1)) * (catalan(cat_input-1)) (((4*cat_input) - 2) * (catalan(cat_input-1)) / (cat_input + 1))使用(((4*cat_input) - 2) * (catalan(cat_input-1)) / (cat_input + 1)) ,这样可以保证除法后得到整数
  • change the type of the first part of the equation to float to force float division: (float((4*cat_input) - 2) / (cat_input + 1)) * (catalan(cat_input-1)) 将方程的第一部分的类型更改为float以强制进行float除法: (float((4*cat_input) - 2) / (cat_input + 1)) * (catalan(cat_input-1))
  • Use python3 instead of python2 as python3 uses decimal division by default 使用python3而不是python2,因为python3默认使用十进制除法
  • Use from __future__ import division to "activate" python3-like division 使用from __future__ import division来“激活”类似于python3的分区

Edit: In general (at least in python) it is advised not to use recursion if possible, as it is not efficient and you may run to problems like recursion limit 编辑:通常(至少在python中)建议不要使用递归,因为它效率不高,并且您可能会遇到递归限制之类的问题

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

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