第二篇隨筆函數
9102年11月底,工科男曹**要算一個方程f(x)=0的根,其中f(x)表達式爲:spa
由於實數範圍內f(x)=0的根太多,因此本文只研究-2<x<2的狀況.這個式子長的太醜了,曹**看着以爲不爽,導之,得一f'(x)指針
這個式子更醜,可是,咱們有牛頓迭代法,能夠構造迭代序列{xn}知足:code
其中f'(xn)不等於0.能夠證實,只要初值選的好,序列能夠收斂到要求的根.而後就能夠寫程序求根了.blog
先上函數圖像(由desmos繪製),看到指定區間上有5個零點.而後,零點附近取值吧.io
再上效果class
結果仍是不錯的.bfc
最後,上代碼.f(x)和f'(x)用委託的方式傳入calc函數.委託注意實例化引用
Public Delegate Function myfunc(x As Double) As Double
Public Function func0(x As Double) As Double Return Exp(x) + Pow(x, 4) * Sin(Pow(x, 3)) End Function Public Function func0derive(x As Double) As Double Return Exp(x) + 4 * Pow(x, 3) * Sin(Pow(x, 3)) + 3 * Pow(x, 6) * Cos(Pow(x, 3)) End Function
Dim f0 As New myfunc(AddressOf func0) Dim fd0 As New myfunc(AddressOf func0derive)
calc的參數中f和fd分別是指向f(x)和f'(x)的函數指針,x0爲初值,eps爲精度,cnt爲迭代次數程序
用傳引用的方式,經過sol返回計算結果.
返回True爲沒有出錯,False爲出錯.
1 Public Function Calc(f As myfunc, fd As myfunc, x0 As Double, eps As Double, cnt As Integer, ByRef sol As Double) As Boolean 2 If cnt <= 0 Or f Is Nothing Or fd Is Nothing Then 3 Return False 4 End If 5 Try 6 sol = 0 7 Dim x As Double = x0, c0 As Integer = 0 8 While Math.Abs(x) > eps And cnt > c0 9 x = x - f(x) / fd(x) 10 c0 += 1 11 End While 12 sol = x 13 Return True 14 Catch ex As Exception 15 Return False 16 End Try 17 End Function