多項式及其導數之值 (線上執行) (原始碼下載)

欲求 f(x)=anxn+an-1xn-1+....+a1x+a0 的多項式及其一階導數在 x=x0 之值,我們可以很直覺地把 x0代入 f(x) 及 f'(x) 多項式之中來求解,程式碼如下:

'求多項式之值
Public Function f(a() As Single, x As Single) As Single
     Dim i As Long
     For i = 0 To UBound(a)
          f = f + a(i) * x ^ i
     Next
End Function

'求一階導數之值
Public Function Df(a() As Single, x As Single) As Single
     Dim i As Long, b() As Single
     ReDim b(0 To UBound(a) - 1)
     For i = 1 To UBound(a)
          b(i - 1) = i * a(i)
     Next
     Df = f(b, x)
End Function

其中參數 a() 是多項式之係數,a(0)=a0、a(1)=a1 依此類推,參數 x 即為 x0,這樣的程式雖然簡單,但是執行起來比較沒有效率,因為 f(x) 在 x=x0 之值可以化簡成 f(x)=(x-x0)*g(x)+b0,這樣可以減少乘法和加法的計算次數,所以我們只要把 b0 解出即可,同樣的道理可應用於 f'(x),例如以下的程式碼使用 Horner method 來解出多項式及其一階導數之值。

副程式:

'求多項式之值
Public Function fx(a() As Single, x As Single) As Single
     Dim i As Long
     fx = a(UBound(a))
     For i = UBound(a) - 1 To LBound(a) Step -1
          fx = a(i) + fx * x
     Next
End Function

'求一階導數之值
Public Function Dfx(a() As Single, x As Single) As Single
     Dim i As Long, fx As Single
     If (UBound(a) - LBound(a) = 0) Then Dfx = 0: Exit Function 
     fx = a(UBound(a)): Dfx = fx
     For i = UBound(a) - 1 To LBound(a) + 1 Step -1
          fx = a(i) + x * fx
          Dfx = fx + x * Dfx
     Next
End Function

參數說明:

a():多項式之係數 a(0)=a0、a(1)=a1 依此類推。

x:即為x0

範例:

Private Sub Command1_Click()
     Dim Keyin As String, a() As Single, x As Single
     Keyin = InputBox("請輸入多項式的係數,低階項的係數先輸入," & _
                  "再輸入高階項的係數,以空白來區隔。" & _
                  vbNewLine & "例如:f(x)=10x^3-5x+3,則依序輸入 3  -5  0  10")
     If Not SepStrToNumArray(Keyin, " ", 0, a) Then MsgBox "輸入了非數值": Exit Sub
     x = Val(InputBox("請輸入x"))
     Debug.Print "此多項式在x=" & x & "的值為 " & fx(a, x)
     Debug.Print "此多項式在x=" & x & "的一階導數為 " & Dfx(a, x)
End Sub

例如 f(x)=10x3-5x+3 在 x=2.3 之值為113.17,一階導數為153.7。

其中 SepStrToNumArray 這個函數,請參閱本站的 將字串拆解成陣列

 


[ 首頁 | 數值分析 | 下一個 ]

This page was written by Jaric on May. 16 , 1998. All rights reserved.

Revised : Apr. 20 , 1999 .

Total pageview since 4/6/1999.