Secant_it方法提供#VALUE! 错误

我正试图在Excel中使用Secant方法来聚合到一个单一的根在Excel中创build一个代码。 x0是第一个猜测, x1是第二个。 由于某种原因,每当我将Secant_itinputExcel单元格时,我都会收到#VALUE! 。 我知道问题不在于Secant,因为当我将它input到单元格中时,我得到了第一个值的正确数字。 我在这里做错了什么?

 Function Secant(x0, x1) Dim x_new As Double x_new = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0)) Secant = x_new End Function Function Secant_it(x0, x1) Dim x_new As Double Dim j As Integer j = 1 x_new = Secant(x0, x1) While j < 21 x0 = x1 x1 = x_new x_new = Secant(x0, x1) j = j + 1 Wend Secant_it = x_new End Function 

我改变了你的function

 Function Secant(x0, x1) Dim x_new As Double Dim a As Double, b As Double a = f(x1) b = f(x0) x_new = x1 - a * (x1 - x0) / (a - b) Secant = x_new End Function Function Secant_it(x0, x1) Dim x_new As Double Dim j As Integer j = 1 x_new = Secant(x0, x1) While j < 21 x0 = x1 x1 = x_new x_new = Secant(x0, x1) Debug.Print x_new j = j + 1 Wend Secant_it = x_new End Function Function f(x) f = (Exp(x / 10) * Cos(x)) - (x ^ 2) End Function 

我注意到你正在获得#VALUE! 因为函数在j = 9之后中断,因为Secant ab变成了0 。 所以除以0除了Secantfunction,你会得到错误。

为了testing的目的,我拿了=Secant_it(2,3)

你的收敛性testing会导致溢出,因为经过一定次数的迭代后,x0和x1变得如此接近以致f(x1)-f(x0)太小。

您应该改变收敛性testing,以检查x0和x1之间的差异是否低于所需的精度。

 Function Secant_it(ByVal x0 As Double, ByVal x1 As Double) Dim x_new As Double Dim j As Integer j = 1 x_new = Secant(x0, x1) 'While j < 21 While Abs(x1 - x0) > 0.000001 ' or any precision you desire x0 = x1 x1 = x_new x_new = Secant(x0, x1) j = j + 1 Wend Secant_it = x_new End Function