Calculating a Square Root in Microsoft .Net with Visual Basic

61
rate or flag this page

By nicomp

This tutorial illustrates an adaptation of the Newton method for calculating square roots. Written in Visual Basic and implemented in Visual Basic .Net, this code simply iterates until a reasonably close approximation is calculated.

The square root approximation is governed by the value of the variable epsilon, declared and initialized in line 5.

    Function SquareRoot(ByVal x As Double) As Double
        Dim g As Double
        Dim root As Double
        Dim tmp As Double
        Const epsilon = 0.00001
        'Add some error handling
        Try
            'Start with a guess in the variable g
            g = 2
            Do While True  ' Infinite Loop. The condition can never become false
                'Calculate x / g
                tmp = x / g
                'Calculate (x/g) squared
                tmp = tmp * tmp
                'Check to see how close we are to the answer
                If System.Math.Abs(tmp - x) <= epsilon Then
                    Return x / g    ' Send the answer back to the calling procedure
                End If
                'Recalculate the guess
                g = ((x / g) + g) / 2
                'Start the loop over
            Loop

        Catch           ' Errors end up here
            MsgBox("Unable to calculate square root: " & Err.Description, MsgBoxStyle.Critical, "oops")
        End Try
    End Function


Visual Basic

Of course, Microsoft has included a square root function in the .Net framework. Our code can be replaced with:

    Function SquareRoot(ByVal x As Double) As Double
        Return Math.Sqrt(x)
    End Function

Comments

RSS for comments on this Hub

SimeyC profile image

SimeyC  says:
4 months ago

Nice method - long time since I did anything in VB!!!

nicomp profile image

nicomp  says:
4 months ago

Thanks!

Submit a Comment

Members and Guests

Sign in or sign up and post using a hubpages account.


optional


  • No HTML is allowed in comments, but URLs will be hyperlinked
  • Comments are not for promoting your hubs or other sites

working