2011-08-03 19 views
0

我正試圖在文件中寫入一個從這個函數計算出來的數據。但是這個函數被稱爲次數。假設在另一個文件中有9個數字,這個函數將計算這9個數字中的每一個的根。這個函數的這9個根應該寫在同一個文件中。但是我在這裏完成的方式會在文件中寫入計算的根,但下一個將在文件中替換它。在這個函數被調用之前,對這9個數字中的每一個都會執行其他的數學函數,因此這些函數會被再次單獨調用。是否可以將它們全部寫入同一個文件中?謝謝。在同一個文件中寫入從一個函數中計算出來的多個數據

def Newton(poly, start): 
    """ Newton's method for finding the roots of a polynomial.""" 
    x = start 
    poly_diff = poly_differentiate(poly) 
    n = 1 
    counter = 0 
    r_i = 0 

    cFile = open("curve.dat", "w") 
    while True: 
     if (n >= 0) and (n < 1): 
      break 

     x_n = x - (float(poly_substitute(poly, x))/poly_substitute(poly_diff, x)) 

     if x_n == x: 
      break 

     x = x_n # this is the u value corresponding to the given time 

     n -= 1 
     counter += 1 
     x = str(x) 
     cFile.write('\n' + x + '\n') 

    if r_i: 
     print "t(u) = ", (x, counter) 

    else: 
     print "t(u) = ", x 


    cFile.close 

以下的建議後,我得到了我改變了代碼如下:

def Newton(poly, start): 
    """ Newton's method for finding the roots of a polynomial.""" 
    x = start 
    poly_diff = poly_differentiate(poly) 
    n = 1 
    counter = 0 

    while True: 
     if (n >= 0) and (n < 1): 
      break 

     x_n = x - (float(poly_substitute(poly, x))/poly_substitute(poly_diff, x)) 

     if x_n == x: 
      break 

     x = x_n # this is the u value corresponding to the given time 

     n -= 1 
     counter += 1 
     yield x 

    Bezier(x) 

def Bezier(u_value) : 
    """ Calculating sampling points using rational bezier curve equation""" 
    u = u_value 

    p_u = math.pow(1 - u, 3) * 0.7 + 3 * u * math.pow(1 - u, 2) * 0.23 \ 
     + 3 * (1 - u) * math.pow(u, 2) * 0.1 + math.pow(u, 3) * 0.52 

    p_u = p_u * w 

    d = math.pow(1 - u, 3) * w + 3 * u * w * math.pow(1 - u, 2) + 3 * (1 - u) *\ 
     w * math.pow(u, 2) + math.pow(u, 3) * w 

    p_u = p_u/d 

    yield p_u 

    plist = list (p_u) 
    print plist 

我跟着貝塞爾()函數,但plist中同樣的事情不會創建,因爲它不打印任何東西。請幫忙。謝謝。

回答

2

你的函數做兩件事情:它計算多項式的根,它的結果寫入到一個輸出文件。功能理想情況下應該做一件事

因此,試着將其分解成一個函數,該函數接收一個多項式並返回一個包含根的列表,然後在一個步驟中將該列表寫入文件。

修改功能將與

yield x 

更換線路

x = str(x) 
cFile.write('\n' + x + '\n') 

然後,你可以調用你的函數類似這樣的最簡單的方法:

roots = list(Newton(polynomial, start)) 

要了解這個,讀約generators。寫結果列表到一個文件,你可以使用此代碼:

with open("curve.dat", "w") as output_file: 
    output_file.write("\n".join(str(x) for x in roots) 
+0

我以前做過這個清單。與列表中的文件一樣,下一個替換當前值。如何在函數被再次調用時附加值?謝謝 – zingy

+0

非常感謝。將嘗試它。 – zingy

+1

或'在牛頓中的根(...):output_file.writeline(root)'。 – katrielalex

1

雖然我不能完全理解你問我想答案可以歸結爲:

打開追加模式的文件,而不是在寫模式。因此,而不是

cFile = open("curve.dat", "w") 

cFile = open("curve.dat", "a") 
+0

謝謝你會嘗試一下,看看會發生什麼。 – zingy

+0

這可行,但問題是我每次運行代碼時,這些值都會在文件中不斷添加,這是不可行的。 – zingy

0

爲什麼要用產量貝塞爾,它不返回多個值,所以你可以改變:

yield p_u 
plist = list (p_u) 
print plist 

到:

print list(p_u) 
return p_u 
相關問題