Python中的无穷连分数

dsekswqp  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(122)

我目前正在尝试在Python中实现一个近似于e常量的函数。

from fractions import Fraction

def fractionalSum(number, array):
    def inside(index, place):
        if place >= 0:
            return Fraction(1, index + place)
        else:
            return Fraction(1, index)

    if number == 0:
        return 0
    elif number == 1:
        return inside(array[number - 1], 0)
    elif number == 2:
        return inside(1, fractionalSum(number - 1, array))
    elif number == 88:
        return inside(array[0], inside(array[1], inside(array[2], inside(array[3], inside(array[4], 0)))))
    else:
        return inside(fractionalSum(number - 2, array), inside(fractionalSum(number - 1, array), 0))

expansion = [1]
it = 1
clock = 0
for i in range(1, 110):
    if clock == 0:
        expansion.append(2 * it)
        it += 1
        clock = 2
    if clock != 0:
        expansion.append(1)
        clock -= 1
print(expansion)
print(2 + fractionalSum(3, expansion))

我目前正在尝试递归来计算它,但代码没有产生正确的结果。
fractionalsum函数中,编号为2的函数应调用与number-1相同的函数,但结果是错误的。
number = 88产生数字5的正确值。我尝试递归地实现它,以便用大于50的数字来近似它。

sqxo8psd

sqxo8psd1#

我还没有研究你到底做错了什么,但是 Continued Fraction 的递归实现应该相当简单,所以我建议这样做:

ONE = Fraction(1, 1)

def continuedFraction(array):
    return _continuedFraction(array, 0)

def _continuedFraction(array, index):
    result = Fraction(array[index], 1)
    if index + 1 < len(array):
        return result + ONE / _continuedFraction(array, index + 1)
    return result

相关问题