[英]writing multiple data calculated from a function in the same file
我試圖將由此函數計算出的數據寫入文件中。 但是該函數稱為次數。 假設另一個文件中有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
我在Bezier()函數中遵循相同的操作,但未創建plist,因為它不會打印任何內容。 請幫忙。 謝謝。
您的函數有兩件事 :計算多項式的根,然后將結果寫入輸出文件。 函數理想上應該做一件事 。
因此,嘗試將其分解為一個函數,該函數接收多項式並返回包含根的列表,然后只需一步就將該列表寫入文件。
修改功能的最簡單方法是替換行
x = str(x)
cFile.write('\n' + x + '\n')
與
yield x
然后,您可以像這樣調用函數:
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)
雖然我不完全理解您的要求,但我認為答案可以歸結為:
以追加模式而不是寫入模式打開文件。 所以代替
cFile = open("curve.dat", "w")
做
cFile = open("curve.dat", "a")
為什么在Bezier中使用yield,它不會返回多個值,因此您可以更改:
yield p_u
plist = list (p_u)
print plist
至:
print list(p_u)
return p_u
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.