[英]How to calculate convergents of continued fraction with big denominator?
我需要從這個公式中找到Dp
和Dq
:
我嘗試使用ContFrac
lib 來完成這個任務:
pip install ContFrac
import contfrac
find_number = 2140e225
value = (1,math.sqrt(find_number))
conv = list(contfrac.convergents(value))
print(conv)
但輸出是奇數,因為數字太大:
0 + 1/(my_sqrt)
來自 SymPy 的方法也不起作用並返回 0。
print(continued_fraction((1//sqrN)))
更新 1:
我在玩 SymPy,發現我應該使用這個庫sqrt
實現。
from sympy import sqrt
lm = continued_fraction((1 / sqrt(number)))
lz = flatten(lm)
print(list(continued_fraction_convergents(lz)))
但是這些會導致內部異常:
PrecisionExhausted: Try simplifying the input, using chop=True, or providing a higher maxn for evalf
但正如我所見,我無法為continued_fraction
操作培養人。 而且我也無法將數字作為十進制傳遞:
decimal.getcontext().prec = 125
lm = continued_fraction((1 / sqrt(decimal.Decimal(find_number))))
ValueError: expecting a rational or quadratic irrational, not 2.16152455423408e-125
剛剛找到一個要點。 它給出與 Wolfram 的 Alpha Convergents[]
相同的值。 但是我不確定第 5 個元素之后的精度,因為 Wolfram 只給出到那個點的值。
import math
import itertools
def continued_fraction(n, d):
while d:
q, r = divmod(n, d)
n, d = d, r
yield q
def alternative_continued_fraction(n, d):
gen = continued_fraction(n, d)
p = next(gen)
for q in gen:
yield p
p = q
yield p - 1
yield 1
def convergents(n, d):
hh, kk, h, k = 0, 1, 1, 0
for x in continued_fraction(n, d):
hh, kk, h, k = h, k, h * x + hh, k * x + kk
yield h, k
decimal.getcontext().prec = 500
print(list(convergents(1, Decimal(find_number).sqrt())))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.