2017-07-24 80 views
1
>>> import math 

#defining first function 
>>> def f(a): 
     return a-math.sin(a)-math.pi/2 

#defining second fuction 
>>> def df(a): 
     return 1-math.cos(a) 

#defining third function which uses above functions 
>>> def alpha(a): 
     return a-f(a)/df(a) 

如何編寫一個代碼,其中alpha(a)取a = 2的起始值,並且alpha(2)的解決方案將在下次成爲輸入。例如:假設alpha(2)達到2.39,因此下一個值將是alpha(2.39)並繼續{最多50次迭代}。有人可以幫我一下嗎?提前致謝。如何在python中輸出輸入

+0

您是在程序運行期間執行此操作,還是希望能夠退出應用程序並繼續使用上次使用的編號? – idjaw

+0

使用for循環? –

+0

@idjaw正在運行程序。謝謝 –

回答

2

可以讓程序迭代與for,並使用一個變量來存儲中間結果

temp = 2    # set temp to the initial value 
for _ in range(50):  # a for loop that will iterate 50 times 
    temp = alpha(temp) # call alpha with the result in temp 
         # and store the result back in temp 
    print(temp)   # print the result (optional) 

print(temp)將打印中間結果。這不是必需的。它僅演示temp變量在整個過程中的更新方式。

+0

因此,在某些時候值不斷重複。是否有任何程序可以從50次迭代中選擇重複值? –

+0

@GarrySaini:通常如果他們開始重複,你可以選擇最後一個值。這意味着你已經找到了該程序的*固定點*。 –

0

您可以將其物化。

import math 

class inout: 
    def __init__(self, start): 
     self.value = start 
    def f(self, a): 
     return a-math.sin(a)-math.pi/2 
    def df(self, a): 
     return 1-math.cos(a) 
    def alpha(self): 
     self.value = self.value-self.f(self.value)/self.df(self.value) 
     return self.value 

然後創建一個inout對象,並在每次調用其alpha方法時,它會給該系列中的下一個值。

demo = inout(2) 
print(demo.alpha())