Find Code: All Words Any of the Words Exact Phrase Home   :   Code   :   Forums   :   Submit   :   Mailing List   :   About   :   Contact
 Code All VB.NET ASP.NET C# VB Classic ASP Classic Snippets Popular Resources Submit Code Forums Articles Tips Links Books Contest Link to us

 Secant method to approximate root of a function Author: BasuDip Website: http://www.geocities.com/basudip_in/vb6code/ Submitted: 12/24/2006 Version: VB6 Compatibility: VB6 Category: Mathematics Views: 16353 Compute a root of a given equation (function of 1 variable) using Secant method. This is my second program on Methods of Numerical Analysis. Declarations: 'none Code: Option Explicit Dim Xp As Single, Xn As Single Private Sub Form_Load() Xp = 1: Xn = 2 ' Initial Values End Sub Rem Modify here to type in the equation and set the initial values ****** Private Function myFunc(ByVal X As Single) As Single myFunc = X * X - Sqr(X) - 2 ' Let F(x)=x*x-x^0.5-2 End Function Private Function SecantRootX(ByVal X0 As Single, _ ByVal X1 As Single) As Single Dim F0 As Single, F1 As Single If X0 = X1 Then SecantRootX = X0 Exit Function End If F0 = myFunc(X0) F1 = myFunc(X1) SecantRootX = (X0 * F1 - X1 * F0) / (F1 - F0) End Function Private Sub Form_Activate() Dim nextXroot As Single, xR As Single, fR As Single, iCount As Integer iCount = 1 Print "=================================================================" Print "X0= " & FormatNumber(Xp, 5) & vbTab & vbTab & "|" & vbTab & vbTab & "F(X0)= " & FormatNumber(myFunc(Xp), 5) Print "------------------------------------------------------------------------------------------------------------" Print "X1= " & FormatNumber(Xn, 5) & vbTab & vbTab & "|" & vbTab & vbTab & "F(X1)= " & FormatNumber(myFunc(Xn), 5) Do While Abs(Xp - Xn) > 0 nextXroot = SecantRootX(Xp, Xn) xR = FormatNumber(nextXroot, 5) fR = FormatNumber(myFunc(nextXroot), 5) Print "------------------------------------------------------------------------------------------------------------" iCount = iCount + 1 Print "X" & iCount & "= " & xR & vbTab & vbTab & "|" & vbTab & vbTab & "F(X" & iCount & ")= "; fR If fR = 0 Then Exit Do DoEvents Xp = Xn: Xn = nextXroot Loop Print "==================================================================" Print " Thus the root of the equation is " & vbTab & FormatNumber(nextXroot, 5) & " ." End Sub