用牛顿迭代法求方程'a * x ^ 3 + b * x ^ 2 + c * x + d = 0, 系数a = 1, b = 2, c = 3, d = 4, x在0附近的一个实数根为1.33333333333。算法代码如下:
Private Sub Command1_Click() '牛顿迭代法
Dim a As Double, b As Double, c As Double, d As Double, xx1 As Double
Dim n As Long
a = 1
b = 2
c = 3
d = 4
xx1 = 0 '初始值为0,x在0附近
Print Nim(a, b, c, d, xx1, n) '方程在XX1附近的根
Print n '迭代次数
End Sub
'牛顿迭代法Newton iteration method
Function Nim(ByVal a As Double, ByVal b As Double, ByVal c As Double, ByVal d As Double, ByVal x0 As Double, ByRef n As Long) As Double
Dim x As Double, y As Double, dy As Double, ydy As Double, i As Long
n = -1 '迭代次数
x = x0
For i = 0 To 1000
y = a * x ^ 3 + b * x ^ 2 + c * x + d
dy = 3 * a * x ^ 2 + 2 * b * x + c
If Abs(x - x0) <= (10 - 5) And x <> x0 Then '迭代到|x-x0|≦10-5时结束
Nim = x
n = i + 1
Exit For
ElseIf dy = 0 Then
n = -1 'X初值不合理,建议另换初值试解
Exit For
End If
ydy = y / dy
x = x - ydy
Next
If i > 1000 Then n = -2 '该方程无解解
End Function