2011-07-23 87 views
0

大家好,我爲我的項目實現了一個三次貝塞爾曲線,我必須將計算出的控制點存儲在一個文件中。我必須使用gnuplot中的輸出文件來查看曲線。在這裏的其中一個帖子,我明白如何實現,但我很困惑如何讓我的輸出到一個文件。當我嘗試它只是寫出它計算的最後一點的值。由於存在循環,所以我應該在文件生成後立即將值寫入文件中。這裏是代碼如下:將計算的數據寫入文件

import math 

points = [(0,0), (5,0), (5,5), (10,5)] 

n = 20 

for i in range(n) : 

     u = i/float(n) 

     x = math.pow(1-u,3) * points[0][0] + 3 * u * math.pow(1-u,2) * points[1][0] \ 
     + 3 * (1-u) * math.pow(u,2) * points[2][0] + math.pow(u,3) * points[3][0] 
     y = math.pow(1-u,3) * points[0][1] + 3 * u * math.pow(1-u,2) * points[1][1] \ 
     + 3 * (1-u) * math.pow(u,2) * points[2][1] + math.pow(u,3) * points[3][1] 

     print "(x,y)=", (x, y)  

有人可以幫助我。謝謝。

回答

1

f = open('somefile.dat', 'w+')打開(並創建)一個文件。用f.write()你可以寫一個字符串到文件中。在你的情況下,你必須與write調用替代print電話:

import math 
points = [(0,0), (5,0), (5,5), (10,5)] 
n = 20 
f = open('somefile.dat', 'w+') 

for i in range(n) : 

    u = i/float(n) 

    x = math.pow(1-u,3) * points[0][0] + 3 * u * math.pow(1-u,2) * points[1][0] \ 
    + 3 * (1-u) * math.pow(u,2) * points[2][0] + math.pow(u,3) * points[3][0] 
    y = math.pow(1-u,3) * points[0][1] + 3 * u * math.pow(1-u,2) * points[1][1] \ 
    + 3 * (1-u) * math.pow(u,2) * points[2][1] + math.pow(u,3) * points[3][1] 

    f.write("(x,y)=(%f, %f)"% (x, y)) 
+1

非常感謝你。這是一個微不足道的問題,但我很愚蠢,我甚至無法做到這一點。 – zingy

0

寫入文件:

f = open("fileName", "w+") 
f.write(someDataToWrite) 

查看更多here