Lagrange Interpolation. (線上執行) (原始碼下載)
嚴格說來,Lagrange Interpolation 也算是一種 Curve fitting,它可以保證 fit 出來的多項式一定通過每一個已知的 f(x),但是由於它所 fit 出來的可能是高階多項式 (如果有 n 個 f(x),fit 出來的多項式為 n-1 階),所以 Lagrange Interpolation 比較適合 noise free 的系統,否則就必須使用其它方法,例如:Least Square 或 Cubic Spline Interpolation。Lagrange 多項式有一個比較重要的應用,就是用來導出數值微分和積分的方法,以及其誤差範圍。
副程式:
Public Function LagrangeInterpolation(x() As Single, f() As Single, dx As Single) As Single Dim i As Long, j As Long, n As Single, m As Single For i = 1 To UBound(x) m = x(i): n = 1 For j = 1 To UBound(x) If i <> j Then n = n * (dx - x(j)) / (m - x(j)) Next LagrangeInterpolation = LagrangeInterpolation + n * f(i) Next End Function參數說明:
x:x值的陣列,陣列基底為 1。
f:f(x)值的陣列,陣列基底為 1。
dx:欲內插的x值。
範例:
Private Sub Command1_Click() Dim Keyin As String, x() As Single, f() As Single, dx As Single Keyin = InputBox("請輸入x值,以空白來區隔。") If Not SepStrToNumArray(Keyin, " ", 1, x) Then MsgBox "輸入了非數值": Exit Sub Keyin = InputBox("請輸入f(x)值,以空白來區隔。") If Not SepStrToNumArray(Keyin, " ", 1, f) Then MsgBox "輸入了非數值": Exit Sub dx = Val(InputBox("請輸入欲內插的x值")) Debug.Print "f(x)在x=" & dx & "的內插值為 " & LagrangeInterpolation(x, f, dx) End Sub其中 SepStrToNumArray 這個函數,請參閱本站的 將字串拆解成陣列。
例如以下的數據以 Lagrange Interpolation 求 f(4.3) 之值:
x 0 1.0 2.0 3.8 5 f(x) 0 0.569 0.791 0.224 -0.185 執行 Command1 並在提示輸入 x 值時輸入 0 1 2 3.8 5,提示輸入 f(x) 值時輸入 0 0.569 0.791 0.224 -0.185,則在 VB 的即時運算視窗可得 f(4.3)= -0.007。
This page was written by Jaric on Jun. 13 , 1998. All rights reserved.
Revised : Jul. 31 , 1998 .