佩尔公式 - 精度误差或数学误差?

时间:2016-08-27 15:51:06

标签: python python-3.x math decimal

我正在做项目Eular的66号,这是关于pell的等式。

我差不多已经解决了,但我没有得到正确的答案,只有答案非常接近正确答案。

我不确定这是精确错误还是数学错误。我正在使用连续分数方法解决它(在this之后(在页面底部))

像61这样的数字应该输出335159612/42912791(十进制的7.81024967591),但我得到29718/3805(7.81024967148488830486202365 ...(续))你可以看到它们非常接近但仍然不完全。

61的等式应该看起来像7 + 1 / (1 + 1 / (4 + 1 / (3 + 1 / (1 + 1 / (2 + 1 / (2 + 1 / (1 + 1 / (3 + 1 / (4 + 1 / 1))))))))),我已经尝试将其输入到各种计算器中并得到与我的代码相同的答案,这让我相信这是一个数学错误,但在哪里?< / p>

这是我的代码,对不起,如果这是一团糟:

# Equation: x^2 * d*Y^2 = 1 where d is any non-square number
import math
from fractions import Fraction
from decimal import getcontext, Decimal

getcontext().prec = 500


def find_fractions(n):
    d = Decimal(n).sqrt()

    safeint = 0
    safe = True #  These two 'safe' are to avoid the IndexError: list index out of range error

    a = ["a", "b", "c", "d"] #  a b c d are also to avoid the list error

    while a[1:int(len(a) / 2)] != a[int(len(a) / 2) + 1:]: #  while the first half (minus the first term) is not the same as the second half (aka find where it repeats)
        a.append(math.floor(d)) # Adds the numbers for the continued fraction (fx 1 / (3 + 1/2 here 2 and 3 are the numbers) 
        d = Decimal(1 / (d - math.floor(d))) #  gets the next number for the continued fraction
        safeint += 1

        if safeint > 4 and safe: #  still to avoid list error
            del a[0]
            del a[0]
            del a[0]
            del a[0]
            safe = False

        print("Fractions: ", a)

    for e in range(0, int(len(a) / 2)): # Second half of the list is useless so this removes the repeats and the last term
        del a[-1]

    print("Useful fractions: ", a)

    g = a[0] #  The first integer (it's special because it doesn't get divided by 1 
    h = Decimal(1 / a[-1]) # last term in list divided by one

    del a[0] # Delete these two because they have already been used
    del a[-1]

    for o in range(1, len(a) + 1): # goes through the list we made with the while loop
        t = Decimal(a[-o] + h)
        h = Decimal(1 / t) 
    # Basically the for-loop does this https://upload.wikimedia.org/wikipedia/en/math/1/1/d/11dc14afeeb64dad18b916638aa287d7.png

    g += h # adds the one that doesn't get devided

    print("x and y =", str(Fraction(g).limit_denominator()))  # Fraction
    # Using the fraction module to make it a fraction (numerator = X and denumerator = Y)
    print(g)  # Decimal

find_fractions(61)

编辑:为代码添加了评论

0 个答案:

没有答案