2016-08-23 94 views
0

我試圖找到任何非平方數的連續分數(直到它重複)。當計算平方根的分數時奇怪的輸出

例如:輸入:23 = [4; 1,3,1,8]

我的代碼工作在很多數字(儘管這是非常笨拙的)。 它適用於23它輸出:

[4, 1, 3, 1, 8, 1, 3, 1] 

(忽略額外的1,3,1)

但是,當我輸入61它永遠不會停止......這裏的線路輸出:

[7, 1, 4, 3, 1, 2, 2, 1, 3, 4, 1, 14, 1, 4, 3, 1, 2, 2, 1, 4, 5, 1, 6900] 

14後不重複像它應該(4,而不是3,4,5和6900是出來的地方)

我有點小白的,當涉及到編碼,所以它會幫助很多,如果一些人能告訴我,爲什麼它不工作,以及如何我應該修復它

這裏是我的代碼:

def find_fractions(n): 
    d = math.sqrt(n) 
    x = 0 
    y = 0 
    safeint = 0 
    safe = True 
    a = ["a", "b", "c", "d"] 
    while a[1:int(len(a)/2)] != a[int(len(a)/2) + 1:]: 
     a.append(math.floor(d)) 
     d = 1/(d - math.floor(d)) 
     print(a) 
     safeint += 1 
     if safeint > 4 and safe: 
      del a[0] 
      del a[0] 
      del a[0] 
      del a[0] 
      safe = False 
    print(a) 

find_fractions(23) 

編輯:不是63,這意味着61

+0

你能提供一個你想達到的一般數學描述嗎? – albert

+0

對我來說'63'的罰款,導致'[7,1,14,14,14,14,14]'。爲64它給'ZeroDivisionError' – vsminkov

+0

基本上我是這樣的:http://math.stackexchange.com/questions/265690/continued-fraction-of-a-square-root並試圖找到任何非持續分數的非 - 平方數 – Sorrells

回答

0

你有什麼是精度誤差。這些計算非常精確,這意味着它們需要許多二進制數字來表示。計算機使用的有限浮點精度有時不足以準確執行此操作。在這一行的某處,你的機器處理這種不準確的行爲正在破壞你的計算。我用decimal模塊來處理這個大的精度。

import math 
from decimal import Decimal 
from decimal import getcontext 

def find_fractions(n): 
    d = Decimal(n).sqrt() 
    x = 0 
    y = 0 
    safeint = 0 
    safe = True 
    a = ["a", "b", "c", "d"] 
    while a[1:int(len(a)/2)] != a[int(len(a)/2) + 1:]: 
     a.append(math.floor(d)) 
     d = Decimal(1/(d - math.floor(d))) 
     print(a) 
     safeint += 1 
     if safeint > 4 and safe: 
      del a[0] 
      del a[0] 
      del a[0] 
      del a[0] 
      safe = False 
    print(a) 

這給了我輸出 [7, 1, 4, 3, 1, 2, 2, 1, 3, 4, 1, 14, 1, 4, 3, 1, 2, 2, 1, 3, 4, 1] 輸入61.爲小數類將默認數量爲28.如果需要,您可以設置小數對象使用更高的精度,像這樣 getcontext().prec = x

這裏是一個Wikipedia page來審查浮點精度。如果您希望我會很樂意爲您提供一些關於使代碼更清潔的建議。

+0

非常感謝!它現在有效! 並感謝您的深入解釋! – Sorrells